directionsService.route is not going through? - google-maps

I'm trying to get the Google Maps Javascript API working, and I've copied the tutorial and directions code, but I can't get directionsService.route to work. Here is my code.
var directionsDisplay;
var directionsService;
var map;
function initialize() {
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({map:map});
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = {
zoom:9,
center: chicago
}
map = new google.maps.Map(document.getElementById("map"), mapOptions);
directionsDisplay.setMap(map);
console.log(google.maps);
console.log(directionsDisplay);
console.log(directionsService);
console.log(directionsService.route);
}
$(document).ready(function() {
function calcRoute() {
// console.log(map);
var start = document.getElementById("origin").value;
var end = document.getElementById("destination").value;
console.log('start');
console.log(start);
console.log('end');
console.log(end);
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
console.log(request);
console.log(google.maps);
console.log(google.maps.DirectionsService);
console.log(directionsDisplay);
console.log(directionsService);
console.log(directionsService.route);
directionsService.route(request, function (result, status) {
console.log('hi');
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
};
$('#origin-search').submit(function() {
console.log('calling calcRoute');
calcRoute();
});
});
The console.log('hi') statement is never reached. Attached are the log statements from the console. I first load index, then do the $('#origin-search').submit(), then rerouted back to loading index. Note that the directionsService.route function logs differently inside initialize() than inside calcRoute().

If I move calcRoute into $(document).ready I get errors because the map isn't initialized yet. I would call calcRoute only after you are sure the map has been initialized.
Here is some working code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Directions Display</title>
<style>
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var directionsDisplay;
var directionsService;
var map;
function initMap() {
directionsService = new google.maps.DirectionsService;
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: chicago
});
directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
calcRoute();
}
function calcRoute() {
var start = "cambridge, ma";
var end = "boston, ma";
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
};
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
</body>
</html>

Related

Google map markers are not visible when loading map in dialog box [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to load google map in dialog box on click of a button. Everything is loading except markers. Please help me what is wrong in my code. How to show markers. When i do not use dialog box then its working fine.
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<script type="text/javascript">
var directionsDisplay;
var directionsService;
var map;
var stepDisplay;
var image ;
var geocoder;
var latitude;
$(function () {
$("#btnShow").click(function () {
$("#dialog").dialog({
modal: true,
title: "Google Map",
width: 600,
hright: 450,
buttons: {
Close: function () {
$(this).dialog('close');
}
},
open: function () {
var mapOptions = {
center: new google.maps.LatLng(19.0606917, 72.83624970000005),
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
directionsService = new google.maps.DirectionsService();
geocoder = new google.maps.Geocoder();
directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.Map($("#dvMap")[0], mapOptions);
directionsDisplay.setMap(map);
// Instantiate an info window to hold step text.
stepDisplay = new google.maps.InfoWindow();
//supress default markers and set route color
directionsDisplay.setOptions( { suppressMarkers: true,
polylineOptions: {
strokeWeight: 5,
strokeOpacity: 1,
strokeColor: 'green'
}
} );
calcRoute();
}
});
});
});
var cList= [];
function showOnMap(){
cList = [];
var coordinates = [];
coordinates.push("ORG");
coordinates.push("18.9542149");
coordinates.push("72.81203529999993");
coordinates.push("hello");
coordinates.push("not");
cList.push(coordinates);
coordinates = [];
coordinates.push("DEST");
coordinates.push("19.2147067");
coordinates.push("72.91062020000004");
coordinates.push("hello");
coordinates.push("not");
cList.push(coordinates);
}
function calcRoute() {
var start;
var end;
var temp;
var waypts = [];
for(var i =0;i<cList.length;i++){
var coord = cList[i];
if(coord[0] == "ORG"){
start = coord[1] +", "+coord[2];
alert("start: "+start);
showSteps(coord[1] , coord[2], coord[3]);
}else if(coord[0]== "DEST"){
end = coord[1] +", "+coord[2];
alert("end: "+end);
showSteps(coord[1] , coord[2],coord[3]);
}else if(coord[0]== "WAYPOINT"){
$("#comments").text("WAYPOINT: ");
temp = coord[1] +", "+coord[2];
//alert("way: "+temp);
waypts.push({
location:temp,
stopover:true});
var text = "reached till this stop ";
showSteps(coord[1] , coord[2],text);
}
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
var marker;
function showSteps(lat, lon, text) {
//alert("showSteps:"+image+" text"+text);
// For each step, place a marker, and add the text to the marker's
// info window. Also attach the marker to an array so we
// can keep track of it and remove it when calculating new
// routes.
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lon),
map: map
});
attachInstructionText(marker, text);
}
function attachInstructionText(marker, text) {
google.maps.event.addListener(marker, 'click', function() {
// Open an info window when the marker is clicked on,
// containing the text of the step.
if(text == ""){
text = "not reached";
}
stepDisplay.setContent(text);
stepDisplay.open(map, marker);
});
}
</script>
<input id = "btnShow" type="button" value="Show Maps" class="fMap" onclick="showOnMap()" />
<div id="dialog" style="display: none">
<div id="dvMap" style="height: 380px; width: 580px;">
</div>
</div>
Your map variable is local to the open function for the dialog:
open: function() {
var mapOptions = {
center: new google.maps.LatLng(19.0606917, 72.83624970000005),
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map($("#dvMap")[0], mapOptions);
Remove the "var" from the beginning of the line that instantiates the google.maps.Map object.
working fiddle
code snippet:
var directionsDisplay;
var directionsService;
var map;
var stepDisplay;
var image;
var geocoder;
var latitude;
$(function() {
$("#btnShow").click(function() {
$("#dialog").dialog({
modal: true,
title: "Google Map",
width: 600,
hright: 450,
buttons: {
Close: function() {
$(this).dialog('close');
}
},
open: function() {
var mapOptions = {
center: new google.maps.LatLng(19.0606917, 72.83624970000005),
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
directionsService = new google.maps.DirectionsService();
geocoder = new google.maps.Geocoder();
directionsDisplay = new google.maps.DirectionsRenderer();
map = new google.maps.Map($("#dvMap")[0], mapOptions);
directionsDisplay.setMap(map);
// Instantiate an info window to hold step text.
stepDisplay = new google.maps.InfoWindow();
//supress default markers and set route color
directionsDisplay.setOptions({
suppressMarkers: true,
polylineOptions: {
strokeWeight: 5,
strokeOpacity: 1,
strokeColor: 'green'
}
});
calcRoute();
}
});
});
});
var cList = [];
function showOnMap() {
cList = [];
var coordinates = [];
coordinates.push("ORG");
coordinates.push("18.9542149");
coordinates.push("72.81203529999993");
coordinates.push("hello");
coordinates.push("not");
cList.push(coordinates);
coordinates = [];
coordinates.push("DEST");
coordinates.push("19.2147067");
coordinates.push("72.91062020000004");
coordinates.push("hello");
coordinates.push("not");
cList.push(coordinates);
}
function calcRoute() {
var start;
var end;
var temp;
var waypts = [];
for (var i = 0; i < cList.length; i++) {
var coord = cList[i];
if (coord[0] == "ORG") {
start = new google.maps.LatLng(coord[1], coord[2]);
showSteps(coord[1], coord[2], coord[3]);
} else if (coord[0] == "DEST") {
end = new google.maps.LatLng(coord[1], coord[2]);
showSteps(coord[1], coord[2], coord[3]);
} else if (coord[0] == "WAYPOINT") {
$("#comments").text("WAYPOINT: ");
temp = coord[1] + ", " + coord[2];
waypts.push({
location: temp,
stopover: true
});
var text = "reached till this stop ";
showSteps(coord[1], coord[2], text);
}
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
var marker;
function showSteps(lat, lon, text) {
// For each step, place a marker, and add the text to the marker's
// info window. Also attach the marker to an array so we
// can keep track of it and remove it when calculating new
// routes.
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lon),
map: map
});
attachInstructionText(marker, text);
}
function attachInstructionText(marker, text) {
google.maps.event.addListener(marker, 'click', function() {
// Open an info window when the marker is clicked on,
// containing the text of the step.
if (text == "") {
text = "not reached";
}
stepDisplay.setContent(text);
stepDisplay.open(map, marker);
});
}
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&ext=.js"></script>
<link rel="stylesheet" type="text/css" href="//code.jquery.com/ui/1.11.4/themes/ui-lightness/jquery-ui.css">
<input id="btnShow" type="button" value="Show Maps" class="fMap" onclick="showOnMap()" />
<div id="dialog" style="display: none">
<div id="dvMap" style="height: 380px; width: 580px;">
</div>
</div>

Add stopover to waypoints

I am having trouble adding stopover points to my google maps route. This is my calcRoute function below. Basically I have an array of latlng objects called waypts and all the points between waypts[0] and waypts[waypts.length-1] should be stopover points. I know I just need to loop through those points and make a stopover with something like this:
<script type="text/javascript">
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var phpway = <?php echo json_encode($phpway); ?>;
var waypts = [];
for(var i = 0; i < phpway.length; i+=2){
waypts.push(new google.maps.LatLng(phpway[i], phpway[i+1]));
}
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = {
zoom: 6,
center: chicago
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
var start = waypts[0];
var end = waypts[waypts.length-1];
var mywaypts = [];
for (var i = 1; i < waypts.length-1; i++) {
mywaypts.push({
location:waypts[i],
stopover:true});
}
var request = {
origin: start,
destination: end,
waypoints: mywaypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
You should not include your start/end points in your waypoints array, and just pass your waypts array in your request this way:
var request = {
origin : start,
destination : end,
waypoints: waypts,
travelMode : google.maps.TravelMode.DRIVING
};
See doc: https://developers.google.com/maps/documentation/javascript/directions?hl=FR#Waypoints

show alert on mouse over of driving route

Alert is not showing when I mouse over on driving route,
can any body help me?
I tried every thing but not works on driving route mouse over.
Note: I am doing this on driving route mouse over not on polyline.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Travel modes in directions</title>
<link href="http://code.google.com//apis/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var haight = new google.maps.LatLng(37.7699298, -122.4469157);
var oceanBeach = new google.maps.LatLng(37.7683909618184, -122.51089453697205);
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: haight
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
}
var points=[];
function calcRoute() {
var selectedMode = document.getElementById('mode').value;
var request = {
origin: haight,
destination: oceanBeach,
// Note that Javascript allows us to access the constant
// using square brackets and a string value as its
// "property."
travelMode: google.maps.TravelMode[selectedMode]
};
directionsService.route(request, function(response, status) {
var myRoute = response.routes[0].legs[0];
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
for (var i = 0; i < myRoute.steps.length; i++) {
for (var j = 0; j < myRoute.steps[i].lat_lngs.length; j++) {
points.push(myRoute.steps[i].lat_lngs[j]);
}
}
}
});
alert("points "+points);
var eventLine = new google.maps.Polyline({
path: points,
visible: true,
strokeOpacity: 0,
zIndex: 1000
});
eventLine.setMap(map);
google.maps.event.addListener(eventLine, "mouseover", function() {
alert("hi")
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="panel">
<b>Mode of Travel: </b>
<select id="mode" onchange="calcRoute();">
<option value="DRIVING">Driving</option>
<option value="WALKING">Walking</option>
<option value="BICYCLING">Bicycling</option>
<option value="TRANSIT">Transit</option>
</select>
</div>
<div id="map-canvas"></div>
</body>
</html>
The DirectionsService doesn't have a mouseover event, a Polyline does. Your code works for me if I move the polyline creation into the DirectionsService callback:
http://www.geocodezip.com/v3_SO_directionsMouseOver.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Travel modes in directions</title>
<link href="http://code.google.com//apis/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var haight = new google.maps.LatLng(37.7699298, -122.4469157);
var oceanBeach = new google.maps.LatLng(37.7683909618184, -122.51089453697205);
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: haight
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
calcRoute();
}
var points=[];
function calcRoute() {
var selectedMode = document.getElementById('mode').value;
var request = {
origin: haight,
destination: oceanBeach,
// Note that Javascript allows us to access the constant
// using square brackets and a string value as its
// "property."
travelMode: google.maps.TravelMode[selectedMode]
};
directionsService.route(request, function(response, status) {
var myRoute = response.routes[0].legs[0];
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
for (var i = 0; i < myRoute.steps.length; i++) {
for (var j = 0; j < myRoute.steps[i].lat_lngs.length; j++) {
points.push(myRoute.steps[i].lat_lngs[j]);
}
}
// alert("points "+points);
var eventLine = new google.maps.Polyline({
path: points,
visible: true,
strokeOpacity: 0,
zIndex: 1000
});
eventLine.setMap(map);
google.maps.event.addListener(eventLine, "mouseover", function() {
alert("hi")
});
} else { alert("Directions request failed: "+status); }
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="panel">
<b>Mode of Travel: </b>
<select id="mode" onchange="calcRoute();">
<option value="DRIVING">Driving</option>
<option value="WALKING">Walking</option>
<option value="BICYCLING">Bicycling</option>
<option value="TRANSIT">Transit</option>
</select>
</div>
<div id="map-canvas"></div>
</body>
</html>

Google direction services.How to detect if geo location is disabled in the browser

If a user has disabled the location feature or if he uses a non geo supported feature.
How to do this programatically? This will get executed,if i enable geo location in my browser ,if i do not enable,i want some other code to get executed.Where i put that other code which will be executed when i do not enable or use non supported browser.
<script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var myOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: chicago
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
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);
}
});
}
</script>
</head>
<body onload="initialize()">
<div>
I would use modernizer to sniff out whether the browser supports geolocation and then take the appropriate action.
if (Modernizr.geolocation) {
//do geolocation/gmaps stuff
} else {
//do something else
}
You can even load shims to give the geolocation functionality to browsers which don't support it. There are examples in the modernizer documentation section.
e.g.
Modernizr.load({
test: Modernizr.geolocation,
yep : 'geo.js',
nope: 'geo-polyfill.js'
});
--Edit
<html>
<head>
<script type="text/javascript" src="modernizer.js"></script>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=&sensor=true"></script>
<script>
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
if (Modernizr.geolocation) {
// Do the geolocation
navigator.geolocation.getCurrentPosition(initializeGeo, handle_error);
} else {
// No geolocation path
initializeNonGeo();
}
}
function handle_error(err) {
alert("Geolocation could not be run");
if (err.code == 1) {
alert("user denied");// user said no!
}
initializeNonGeo();
}
function initializeGeo() {
alert("has geolocation");
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var myOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: chicago
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
}
function initializeNonGeo() {
alert("no geolocation"); //do non geo stuff.
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width: 500px; height: 300px"></div>
</body>
</html>

Google map driving direction source code for their example?

Google gave an example
http://googlemapsapi.blogspot.com/2007/05/driving-directions-support-added-to.html
Is the source code available somewhere or a tutorial on that precise example ?
Here's a very basic example using the v3 API:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API v3 Directions Example</title>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body style="font-family: Arial; font-size: 12px;">
<div style="width: 600px;">
<div id="map" style="width: 280px; height: 400px; float: left;"></div>
<div id="panel" style="width: 300px; float: right;"></div>
</div>
<script type="text/javascript">
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.Map(document.getElementById('map'), {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('panel'));
var request = {
origin: 'Chicago',
destination: 'New York',
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
</script>
</body>
</html>
Screenshot:
Code to get route, legs and other data using Latitude/longitude OR using Address without google map in JavaScript using v3 API:
<script src="https://maps.googleapis.com/maps/api/js?v=3&key=<key>&libraries=places"></script>
<script>
var directionsService = new google.maps.DirectionsService();
var start_lat = "41.8781136";
var start_lon = "-87.6297982";
var end_lat = "40.7127753";
var end_lon = "-74.0059728";
// Using Latitude and longitude
var request = {
origin: new google.maps.LatLng(start_lat, start_lon),
destination: new google.maps.LatLng(end_lat, end_lon),
optimizeWaypoints: true,
avoidHighways: false,
avoidTolls: false,
travelMode: google.maps.TravelMode.DRIVING
};
//Using plain address
// var request = {
// origin: { query: "Chicago, IL, USA" },
// destination: { query: "New York, NY, USA" },
// travelMode: google.maps.TravelMode.DRIVING,
// };
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var route = response.routes[0];
var leg = response.routes[0].legs[0];
var polyline = route.overview_polyline;
var distance = route.legs[0].distance.value;
var duration = route.legs[0].duration.value;
console.log(route); // Complete route
console.log(distance); // Only distance
console.log(duration); // Only duration
console.log(leg); // Route options/list
console.log(polyline); // Polyline data
}
});
</script>