Not giving me directions - javascript

I might not be understanding how this works, but if I enter in #Model.name which would find an address (just make one up for your testing purposes) the following javascript should find me, find the destination and find me directions.
But it doesn't. Why doesn't it? There are no console errors.
function success(position) {
var s = document.querySelector('#status');
if (s.className == 'success') {
// not sure why we're hitting this twice in FF, I think it's to do with a cached result coming back
return;
}
s.innerHTML = "found you!";
s.className = 'success';
var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcanvas';
mapcanvas.style.height = '400px';
mapcanvas.style.width = '560px';
document.querySelector('article').appendChild(mapcanvas);
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom: 15,
center: latlng,
mapTypeControl: false,
navigationControlOptions: { style: google.maps.NavigationControlStyle.SMALL },
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("mapcanvas"), myOptions);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "You are here! (at least within a " + position.coords.accuracy + " meter radius)"
});
var request = {
origin: latlng,
destination: '#Model.id',
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function error(msg) {
var s = document.querySelector('#status');
s.innerHTML = typeof msg == 'string' ? msg : "failed";
s.className = 'fail';
// console.log(arguments);
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
error('not supported');
}

you must define the map-option for directionsDisplay

Related

Cordova Device Ready Initialize Google Map

I have this Javascript code on Google maps with geolocation and direction and I am using it in cordova , it gives me problems because it lacks the event Deviceready.
I tried to put it , but it was not working.
You are able to add it in the right way ?
Code:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
// default location. When geolocation tracks the client, this variable is set to that location
function initialize() {
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
directionsDisplay = new google.maps.DirectionsRenderer();
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
//here there is marker
directionsDisplay.setMap(map);
map.setCenter(mylocation);
}
function updateRoute() {
calcRoute(mylocation);
}
function calcRoute(start) {
var start = mylocation;
var end = document.getElementById('end').value;
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.WALKING,
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
mylocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
//document.getElementById('start').value = ;
if (map) {
calcRoute(position.coords.latitude +','+ position.coords.longitude);
map.setCenter(mylocation);
//*Posizione Utente*//
var image = 'user.png'
var marker1 = new google.maps.Marker({
position: mylocation,
map: map,
title: 'ciao!',
icon: image
});
google.maps.event.addListener(marker1, 'click', function() {
infowindow1.open(map,marker1);
});
var infowindow1 = new google.maps.InfoWindow({
content: '<img src="user.png">Sono Qui.....'
});
}
})
}
google.maps.event.addDomListener(window, 'load', initialize);

google maps v3 setCenter for map

I am not sure where to add the setCenter as my map is currently centering to the LatLng above where i put my var setCenter code below, my javascript is terrible so I don't even know really what is going on below, i just copy pasted the code down there, so for me to look at other examples on stackexchange will not work, if anyone knows where i would put the setCenter would be much appreciated.
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize() {
var latlng = new google.maps.LatLng(-33.8333406,18.6470022);
var setCenter = new google.maps.LatLng(37.4419, -122.1419);
directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var map = new google.maps.Map(document.getElementById("map"),myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
var marker = new google.maps.Marker({
position: latlng,
map: map,
title:"Get Directions"
});
}
function calcRoute() {
var start = document.getElementById("routeStart").value;
var end = "-33.8333406,18.6470022";
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
if (status == 'ZERO_RESULTS') {
alert('No route could be found between the origin and destination.');
} else if (status == 'UNKNOWN_ERROR') {
alert('A directions request could not be processed due to a server error. The request may succeed if you try again.');
} else if (status == 'REQUEST_DENIED') {
alert('This webpage is not allowed to use the directions service.');
} else if (status == 'OVER_QUERY_LIMIT') {
alert('The webpage has gone over the requests limit in too short a period of time.');
} else if (status == 'NOT_FOUND') {
alert('At least one of the origin, destination, or waypoints could not be geocoded.');
} else if (status == 'INVALID_REQUEST') {
alert('The DirectionsRequest provided was invalid.');
} else {
alert("There was an unknown error in your request. Requeststatus: \n\n"+status);
}
}
});
}
This line:
var latlng = new google.maps.LatLng(-33.8333406,18.6470022);
gives you a latlng object, which you later used in map options, to center the map.
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
If you want to use setCenter latlng object to be used as center of map, then change it in map options.
var setCenter = new google.maps.LatLng(37.4419, -122.1419);
var myOptions = {
zoom: 8,
center: setCenter, // setCenter latlng, defined above will be used to center tha map
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};

Function to determine if geo-location is enabled

I have a function that determines if the users broswer is geo-location enabled and if the user has geo-location enabled it is to display a Google map, if it isn't it then displays a different map.
function init_maps() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geoInfo, noGeoInfo, { timeout: 20000 });
} else {
noGeoInfo();
}
function geoInfo(position) {
navigator.geolocation.getCurrentPosition(function (position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var coords = new google.maps.LatLng(latitude, longitude);
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 15,
center: coords,
mapTypeControl: true,
navigationControlOptions:
{
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapContainer"), mapOptions);
directionsDisplay.setMap(map);
var request = {
origin: coords, //start point for directions
destination: '54.861283, -6.326805', //end point for directions
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
});
//}
function noGeoInfo() {
var location = new google.maps.LatLng(54.861283, -6.326805);
var mapOptions = {
center: location,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("mapContainer"), mapOptions);
marker = new google.maps.Marker({
position: location,
map: map
});
}
}
}
The function init_maps() is called when the user clicks on a link. The problem is that nothing is displayed in the div when the page loads, if I remove:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geoInfo, noGeoInfo, { timeout: 20000 });
} else {
noGeoInfo();
}
function geoInfo(position) {
the map then loads as expected. Why is it not being displayed if I have the if else to determine if geo-location is enabled?

Adding info boxes to Google Directions

I'm having trouble adding click-able info boxes to my google map Directions.
I can get this to work within the initialize function, but I need to get this to work when I add the extra markers via my xml file. See full code below.
Thanks for any help..
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var stepDisplay;
var map;
var markersArray;
var markers = [];
var infowindow;
function initialize() {
var latlng = new google.maps.LatLng( <? echo $lat; ?> , <? echo $lon; ?> );
var rendererOptions = {
draggable: true
};
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
}
//ADD LIST
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
function calcRoute() {
var travelMode = 'DRIVING';
var start = $("#routeStart").val();
var via = $("#routeVia2").val();
var end = $("#routeVia").val();
var waypoints = [];
if (via != '') {
waypoints.push({
location: via,
stopover: true
});
}
var request = {
origin: start,
destination: end,
waypoints: waypoints,
unitSystem: google.maps.UnitSystem.IMPERIAL,
travelMode: google.maps.DirectionsTravelMode[travelMode]
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var myRoute = response.routes[0];
var txtDir = '';
for (var i = 0; i < myRoute.legs[0].steps.length; i++) {
txtDir += myRoute.legs[0].steps[i].path + "";
}
var strLAT = "" + txtDir;
//---------------------------------------------------------
//SEND DATA TO URL
var DATET = $("#DATET").val();
var TIMET = $("#TIMET").val();
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("POST", 'MYPHPFILE', true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send("LATLON=" + strLAT + "&getURL=" + end + "&TIMET=" + TIMET + "&DATET=" + DATET);
//-------------------------------------------------------
//RETURN DATA FOR PLACE MARKERS
var getURL = "MYXMLFILE" + end + ".xml";
jQuery.get(getURL, function(data) {
jQuery(data).find("marker").each(function() {
var eachMarker = jQuery(this);
var markerCoords = new google.maps.LatLng(
parseFloat(eachMarker.find("Lat").text()),
parseFloat(eachMarker.find("Lng").text())
);
var header = eachMarker.find("title").text();
var content = eachMarker.find("Content").text();
var wxicon = eachMarker.find("icon").text();
//--------------------------------------------------------------------------
//ADD INFO BOXES
var contentString = "HELLO WORLD";
var infowindow = new google.maps.InfoWindow({
content: contentString,
});
//--------------------------------------------------------------------------
marker = new google.maps.Marker({
position: markerCoords,
icon: wxicon,
map: map,
animation: google.maps.Animation.DROP,
title: header,
});
});
});
//--------------------------------------------------------------------------
} else {
//ERROR MESSAGES
if (status == 'ZERO_RESULTS') {
alert('No route could be found between the origin and destination.');
} else if (status == 'INVALID_REQUEST') {
alert('The DirectionsRequest provided was invalid.');
} else {
alert("There was an unknown error in your request. Requeststatus: nn" + status);
}
}
});
}
Fixed, I changed marker to this, see below. Answer at http://you.arenot.me/2010/06/29/google-maps-api-v3-0-multiple-markers-multiple-infowindows/
//ADD INFO BOX
var contentString = "HELLO WORLD";
var infowindow = new google.maps.InfoWindow({
content: htmls,
});
//--------------------------------------------------------------------------
marker = new google.maps.Marker({
position: markerCoords,
icon: wxicon,
map: map,
animation: google.maps.Animation.DROP,
title: header,
html: htmls,
});
var contentString = "HELLO WORLD";
var infowindow = new google.maps.InfoWindow({
content: htmls,
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
});
});

How to edit default marker in google maps

Kindly check this map view: http://gmaps-samples-v3.googlecode.com/svn/trunk/map_language/map_lang.html
If you click on A or B, it will show location name in default marker. I wish to show some custom texts here. How can I do that?
My JavaScript code for this is:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var oldDirections = [];
var currentDirections = null;
//getting latitude and longitude from address
var latitude;
var longitude;
var geocoder = new google.maps.Geocoder();
var address = "Downtown Berkeley";
geocoder.geocode( { "address": address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
// do something with the geocoded result
//
latitude = results[0].geometry.location.lat()
longitude = results[0].geometry.location.lng()
alert(latitude )
}
});
//map initialize
function initialize() {
var myOptions = {
zoom: 13,
center: new google.maps.LatLng(-33.879,151.235),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//adding marker
var marker = new google.maps.Marker
(
{
position: new google.maps.LatLng(latitude , longitude),
map: map,
title: "Click me"
}
);
var infowindow = new google.maps.InfoWindow({
content: "Location info:<br/>Country Name:<br/>LatLng:"
});
google.maps.event.addListener(marker, "click", function () {
// Calling the open method of the infoWindow
infowindow.open(map, marker);
});
directionsDisplay = new google.maps.DirectionsRenderer({
"map": map,
"preserveViewport": true,
"draggable": true
});
directionsDisplay.setPanel(document.getElementById("directions_panel"));
google.maps.event.addListener(directionsDisplay, "directions_changed",
function() {
if (currentDirections) {
oldDirections.push(currentDirections);
}
currentDirections = directionsDisplay.getDirections();
});
calcRoute();
}
function calcRoute() {
var start = "El Cerrito del Norte";
var end = "Downtown Berkeley";
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
You set that content in the createInfoWindow() method.

Categories

Resources