I am trying to get the directions services working on google maps api v3.
It is a webapp for smartphones where the user can get directions from where they are (GeolocationMarker) to a static (hardcoded) location defined by a lat and long.
The map centres on the hard coded lat and long, and then I have an icon (gps.png) that onclick should calculate and plot the directions between the two points.
I am not overly strong in javascript and this is essentially a mashup of code...can anyone see what I have done wrong and why this wont work?
Javascript is:
<code>
var map, GeoMarker;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var arena = new google.maps.LatLng(43.684782688659126,-79.2992136269837);
var mapOptions = {
zoom: 12,
center: arena,
panControl: false,
zoomControl: false,
streetViewControl: false,
mapTypeControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
directionsDisplay.setMap(map);
var marker1 = new MarkerWithLabel({
position: arena,
draggable: false,
raiseOnDrag: false,
map: map,
icon: "images/lax-pin1.png",
labelContent: "Ted Reeve Arena",
labelAnchor: new google.maps.Point(25, 0),
labelClass: "pin", // the CSS class for the label
labelStyle: {opacity: 0.95}
});
GeoMarker = new GeolocationMarker();
GeoMarker.setCircleOptions({fillColor: '#808080'});
google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function(e) {
map.setCenter(e.latLng);
map.fitBounds(e.latLngBounds);
});
google.maps.event.addListener(GeoMarker, 'geolocation_error', function(e) {
alert('There was an error obtaining your position. Message: ' + e.message);
});
GeoMarker.setMap(map);
}
function calcRoute() {
var request = {
origin: GeoMarker,
destination: marker1,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</code>
The html is an onclick div tag for the calcRoute function
Thanks for any help....
There is an error reported:
TypeError: e is undefined
for line
map.setCenter(e.latLng);
Event listener
google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function(e) {
map.setCenter(e.latLng);
map.fitBounds(e.latLngBounds);
});
should be changed to
google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function(e) {
//map.setCenter(e.latLng);
//map.fitBounds(e.latLngBounds);
map.setCenter(GeoMarker.getPosition());
map.fitBounds(GeoMarker.getBounds());
});
request should be changed to:
var request = {
origin: GeoMarker.getPosition(),
destination: marker1.getPosition(),
travelMode: google.maps.TravelMode.DRIVING
};
because origin/destination expects string or valid LatLng
Update: I forgot this change: marker1 has to be changed to global:
var map, GeoMarker;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var marker1;
Okay, I got it to work, but not pretty. This is what I did
function calcRoute() {
var arena1 = new google.maps.LatLng(43.684782688659126,-79.2992136269837);
var request = {
origin: GeoMarker.getPosition(),
destination: arena1,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
Related
I would like to make a Directions on google map , and there is my code.
In the code , there are four Markers on it.
I want that I can decide which markers I want to hide.
How to set the marker visible on google map draggable direcion?
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: 22.65, lng: 120.30}
});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
panel: document.getElementById('right-panel')
});
directionsDisplay.addListener('directions_changed', function() {
computeTotalDistance(directionsDisplay.getDirections());
});
displayRoute('22.650927, 120.328185' , '22.656672, 120.307596', directionsService,
directionsDisplay);
}
function displayRoute(origin, destination, service, display) {
service.route({
origin: origin,
destination: destination,
waypoints: [{location:new google.maps.LatLng(22.651682, 120.324307)},{location:new google.maps.LatLng(22.655168, 120.320009)}],
travelMode: google.maps.TravelMode.DRIVING,
avoidTolls: true
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
display.setDirections(response);
} else {
alert('Could not display directions due to: ' + status);
}
});
}
The picture shows the directions look like.
If you are using jQuery, try getting the markers like this:
var markers = $('#map_canvas').gmap('get','markers');
I'm using the Google Maps API on Google Maps.
The thing is that, It shows me several stations throughout the path, labeling them as A-B-C-D...Z, but I need to change it as 1-2-3-4-..99,
Here is my code;
directionsService.route({
origin: $( "#input-directions-start-point" ).val(),
destination: $( "#input-directions-end-point" ).val(),
waypoints: waypts, //other duration points
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
console.log(response);
} else {
vts.alertDialog( window.localization.error,
window.localization.error_direction_calculate + ": " + status,
BootstrapDialog.TYPE_DANGER);
}
});
Here is the Screen Shot;
Thanks in Advance
google.maps.DirectionsRendererOptions has property suppressMarkers which when you set to true, will only render the path but not markers.
You can then render the markers yourself using for example google.maps.Marker, which has label attribute using which you can specify the label inside the marker, which can be for example a number (You can also create your own very custom marker by extending google.maps.OverlayView class, or use RichMarker library). The position of the markers on route can be parsed from response object of directionsService.
More in docs.
Working example:
function init(){
directionsService = new google.maps.DirectionsService();
var pos = new google.maps.LatLng(41.218624, -73.748358);
var myOptions = {
zoom: 15,
center: pos,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), myOptions);
directionsDisplay = new google.maps.DirectionsRenderer({map: map, suppressMarkers: true});
directionsService.route({
origin: "New York",
destination: "Chicago",
waypoints: [{location:"Philadelphia"}, {location:"Boston"}], //other duration points
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var my_route = response.routes[0];
for (var i = 0; i < my_route.legs.length; i++) {
var marker = new google.maps.Marker({
position: my_route.legs[i].start_location,
label: ""+(i+1),
map: map
});
}
var marker = new google.maps.Marker({
position: my_route.legs[i-1].end_location,
label: ""+(i+1),
map: map
});
} else {
vts.alertDialog( window.localization.error,
window.localization.error_direction_calculate + ": " + status,
BootstrapDialog.TYPE_DANGER);
}
});
}
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("maps", "3",{other_params:"sensor=false"});
</script>
<body style="margin:0px; padding:0px;" onload="init()">
<div id="map" style="height:400px; width:500px;"></div>
</body>
Currently I have encounter a problem. I used and changed sample API to draw route for two points. Point A is current location. Point B is one of the multiple markers' location. Those markers are created which I call nearby search function.
function showInfoWindow() {
var marker = this;
places.getDetails({
placeId: marker.placeResult.place_id
},
function(place, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
return;
}
infoWindow.open(map, marker);
buildIWContent(place);
});
var clickLat = marker.position.lat();
var clickLon = marker.position.lng();
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
var directionsService = new google.maps.DirectionsService();
showRoute(clickLat, clickLon, directionsDisplay, directionsService);
}
function showRoute(clickLat, clickLon, directionsDisplay, directionsService) {
var pointA = {
lat: currentLat,
lng: currentLon
};
var pointB = {
lat: clickLat,
lng: clickLon
};
directionsDisplay.setOptions({
suppressMarkers: true
});
//directionsDisplay.setMap(map);
//directionsDisplay.setDirections({ routes: [] });
// Set destination, origin and travel mode.
var request = {
destination: pointB,
origin: pointA,
travelMode: google.maps.TravelMode.DRIVING
};
//directionsDisplay.setMap(null);
// Pass the directions request to the directions service.
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// Display the route on the map.
//directionsDisplay.set('directions', null);
//directionsDisplay.setMap(map);
//directionsDisplay.setDirections({ routes: [] });
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
These codes could draw route for two points already. But the problem is when I click one marker call the showInfoWindow() it will draw one route, and click another one when it will call the showInfoWindow() again it will draw another route remaining the previous one route.I want to clear the previous one route. Tried all the methods online and could not find the reason.
If you only want one directions result displayed on the map at the time, only create and use one instance of the DirectionsRenderer, currently you create a new one for every result from the DirectionsService.
proof of concept fiddle
code snippet:
var geocoder;
var map;
var places;
var infoWindow = new google.maps.InfoWindow();
//Jersey City, NJ, USA
var currentLat = 40.7281575;
var currentLon = -74.0776417;
// global reference to the DirectionsRenderer
var directionsDisplay;
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
places = new google.maps.places.PlacesService(map);
// initialize the global DirectionsRenderer
directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
var marker1 = new google.maps.Marker({ /* New York, NY, USA */
position: {
lat: 40.7127837,
lng: -74.0059413
},
placeResult: {
place_id: "ChIJOwg_06VPwokRYv534QaPC8g"
},
map: map
});
google.maps.event.addListener(marker1, 'click', showInfoWindow);
var marker2 = new google.maps.Marker({ /* Newark, NJ, USA */
position: {
lat: 40.735657,
lng: -74.1723667
},
placeResult: {
place_id: "ChIJHQ6aMnBTwokRc-T-3CrcvOE"
},
map: map
});
google.maps.event.addListener(marker2, 'click', showInfoWindow);
var bounds = new google.maps.LatLngBounds();
bounds.extend(marker1.getPosition());
bounds.extend(marker2.getPosition());
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initialize);
function showInfoWindow() {
var marker = this;
places.getDetails({
placeId: marker.placeResult.place_id
},
function(place, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
return;
}
infoWindow.open(map, marker);
buildIWContent(place);
});
var clickLat = marker.position.lat();
var clickLon = marker.position.lng();
var directionsService = new google.maps.DirectionsService();
showRoute(clickLat, clickLon, directionsDisplay, directionsService);
}
function showRoute(clickLat, clickLon, directionsDisplay, directionsService) {
var pointA = {
lat: currentLat,
lng: currentLon
};
var pointB = {
lat: clickLat,
lng: clickLon
};
directionsDisplay.setOptions({
suppressMarkers: true
});
//directionsDisplay.setMap(map);
//directionsDisplay.setDirections({ routes: [] });
// Set destination, origin and travel mode.
var request = {
destination: pointB,
origin: pointA,
travelMode: google.maps.TravelMode.DRIVING
};
//directionsDisplay.setMap(null);
// Pass the directions request to the directions service.
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// Display the route on the map.
//directionsDisplay.set('directions', null);
//directionsDisplay.setMap(map);
//directionsDisplay.setDirections({ routes: [] });
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
html,
body,
#map_canvas {
height: 500px;
width: 500px;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="map_canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>
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
};
I try to make directions for my current position and marker coordinate. so i get latitude and longitude using getcurrentposition. then, i mark it.
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var node = new google.maps.LatLng(-7.276442,112.791174);
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'),
mapOptions);
directionsDisplay.setMap(map);
navigator.geolocation.getCurrentPosition(function(position) {
pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var marker = new google.maps.Marker({
position : pos,
map: map,
title:'Lokasi Anda'
});
var marker1 = new google.maps.Marker({
position : node,
map: map,
title:'Lokasi Anda'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
}
then, I calculate it using this function.
function calcRoute() {
var request = {
origin:pos,
destination:node,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
but why i can't see direction from pos to node. any suggestion ?
If I call the calcRoute function (and pass in the "pos" and "node" locations, it can't find directions between where I am (in the US) and where the point is located (Raya Its, Sukolilo, Surabaya City, East Java 60117, Republic of Indonesia). The DirectionsService returns a status of "ZERO_RESULTS".
ZERO_RESULTS No route could be found between the origin and destination.
working example
function calcRoute(pos,node) {
var directionsService = new google.maps.DirectionsService();
var request = {
origin:pos,
destination:node,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else { alert("Directions failed: "+status); }
});
}