google maps directionsService giving wrong results - google-maps-api-3

I am trying to get distance in miles and estimated time with googles directionsService. It sort of works but I know the results its giving me are incorrect. The distance and time are too short? I need results in driving mode. A sample of the code is :
HTML
<input id="s_lat" value="52.441334" />
<input id="s_lng" value="-1.654737" />
<input id="d_lat" value="52.450439" />
<input id="d_lng" value="-1.729660" />
JS
var n_start = s_lat + ',' + s_lng;
var n_end = d_lat + ',' + d_lng;
function getdistance() {
var directionsService = new google.maps.DirectionsService();
var request = {
origin : n_start,
destination : n_end,
travelMode : google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
durationInTraffic: true
};
directionsService.route(request, function(response, status) {
if ( status == google.maps.DirectionsStatus.OK ) {
alert (response.routes[0].legs[0].duration.value);
alert (response.routes[0].legs[0].distance.value);
}
else {
// oops, there's no route between these two locations
}
});
}

The result I get with the posted code is NOT_FOUND, I don't get a distance. A comma separated string is not a google.maps.LatLng or a google.maps.LatLngLiteral, it is treated as an address and geocoded before returning the results.
This:
var n_start = s_lat + ',' + s_lng;
var n_end = d_lat + ',' + d_lng;
Should be (google.maps.LatLngLiteral):
var n_start = {lat: parseFloat(s_lat.value), lng: parseFloat(s_lng.value)};
var n_end = {lat: parseFloat(d_lat.value), lng: parseFloat(d_lng.value)};
Or (google.maps.LatLng):
var n_start = new google.maps.LatLng(s_lat.value,s_lng.value);
var n_end = new google.maps.LatLng(d_lat.value,d_lng.value);
Proof of concept fiddle
Code snippet:
function initMap() {
var n_start = new google.maps.LatLng(s_lat.value,s_lng.value);
var n_end = new google.maps.LatLng(d_lat.value,d_lng.value);
function getdistance() {
var directionsService = new google.maps.DirectionsService();
var request = {
origin: n_start,
destination: n_end,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
durationInTraffic: true
};
console.log(JSON.stringify(request));
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
console.log("duration=" + response.routes[0].legs[0].duration.value + " seconds");
console.log("distance=" + response.routes[0].legs[0].distance.value + " meters");
document.getElementById('result').innerHTML = "distance=" + (response.routes[0].legs[0].distance.value / 1000).toFixed(2) + " km<br>duration=" + (response.routes[0].legs[0].duration.value / 60).toFixed(2) + " minutes";
new google.maps.DirectionsRenderer({
map: new google.maps.Map(document.getElementById('map')),
directions: response
})
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
getdistance();
}
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<input id="s_lat" value="52.441334" />
<input id="s_lng" value="-1.654737" />
<input id="d_lat" value="52.450439" />
<input id="d_lng" value="-1.729660" /><br>
<div id="result"></div>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>

Related

Pedestrian and bicycle route longer then car route

I'm using Here Maps API for calculating routes, most of them are for bycicle and pedestrian.
What I found very strange, is that sometimes the car-route is much smaller then the pedestrian or bicycle route.
I have one example in attachement (images route pedestrian and car).
This is from adres:
Steenweg 66, 9473 Denderleeuw, Belgium
To
Grooten Moortelhoek 17, 9473 Denderleeuw, Belgium
If I do the same in Google Maps, then it's ok...
Any suggestions …
Best regards
Bart
Code:
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<script src="http://js.api.here.com/v3/3.0/mapsjs-core.js" type="text/javascript" charset="utf-8"></script>
<script src="http://js.api.here.com/v3/3.0/mapsjs-service.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-ui.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-mapevents.js"></script>
<link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.0/mapsjs-ui.css?dp-version=1526040296" />
</head>
<body>
<div id="mapContainer" style="width: 67%; height: 100%; float:left; border: 1px solid black"></div>
<div id="panel" style="position:absolute; width:29%; left:67%; height:97%; background:inherit; " ></div>
<script>
var url = window.location.toString();
var appid = '';
var appcode = '';
var typeaction = '';
var formatadres = '';
var fromadres = '';
var toadres = '';
var fromlatitude = '';
var fromlongitude = '';
var tolatitude = '';
var tolongitude = '';
var minrelevance = 0;
var routemode = '';
// Create the parameters for the routing request:
// var routingParameters = {
// // The routing mode:
// mode: 'fastest;car',
// // The start point of the route:
// waypoint0: fromlatlng,
// // The end point of the route:
// waypoint1: tolatlng,
// // To retrieve the shape of the route we choose the route
// representation: 'display',
// routeattributes : 'waypoints,summary,shape,legs',
// };
// omzetten van tijd in minuten en seconden
Number.prototype.toMMSS = function () {
return Math.floor(this / 60) +' min. '+ (this % 60) + ' sec.';
}
//get the parameters from url
url.match(/\?(.+)$/);
var params = RegExp.$1;
readUrlParameters(params);
// Initialize the platform object:
var platform = new H.service.Platform({
'app_id': appid,
'app_code': appcode
});
var defaultLayers = platform.createDefaultLayers();
var map = new H.Map(
document.getElementById('mapContainer'),
defaultLayers.normal.map, {
center: {lat: 50.8121, lng: 4.2190},
zoom: 9
});
var routeInstructionsContainer = document.getElementById('panel');
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
var ui = H.ui.UI.createDefault(map, defaultLayers);
// Get an instance of the routing service:
var router = platform.getRoutingService();
// Get an instance of the geocoding service:
var geocoder = platform.getGeocodingService();
// CALLBACK FUNCTIONS
// Define a callback function to process the reverse geocoding response:
var onShowlatlong = function(result) {
var location = result.Response.View[0].Result[0];
// Create an InfoBubble at the returned location with
// the address as its contents:
// ui.addBubble(new H.ui.InfoBubble({
// lat: location.Location.DisplayPosition.Latitude,
// lng: location.Location.DisplayPosition.Longitude
// }, { content: '<p class="H_ib_body">' + location.Location.Address.Label + '</p>'}));
// Create a marker for the point:
var adressMarker = new H.map.Marker({
lat: location.Location.DisplayPosition.Latitude,
lng: location.Location.DisplayPosition.Longitude
});
// Add the route polyline and the two markers to the map:
map.addObjects([adressMarker]);
map.setCenter({lat: location.Location.DisplayPosition.Latitude, lng: location.Location.DisplayPosition.Longitude});
map.setZoom(17);
};
// Define a callback function to process the geocoding response:
var onShowadress = function(result) {
var locations = result.Response.View[0].Result,
position,
marker;
// alert(result.Response.View[0].Result[0].Relevance * 100);
if (result.Response.View[0].Result[0].Relevance * 100 < minrelevance) {
alert("Adres niet gevonden");
return;
}
// Add a marker for each location found
for (i = 0; i < locations.length; i++) {
position = {
lat: locations[i].Location.DisplayPosition.Latitude,
lng: locations[i].Location.DisplayPosition.Longitude
};
// alert(result.Response.View[0].Result[0].MatchLevel);
document.getElementById("fromLatitudechar").value = position.lat;
document.getElementById("fromLongitudechar").value = position.lng;
document.getElementById("fromRelevance").value = result.Response.View[0].Result[0].Relevance;
marker = new H.map.Marker(position);
map.addObject(marker);
map.setCenter({lat: position.lat, lng: position.lng});
map.setZoom(17);
}
};
// Define a callback function to process the calcroutlatlng:
var onCalcRoutelatlng = function(result) {
var route,
routeShape,
startPoint,
endPoint,
linestring;
if (typeof result.response === 'undefined') {
alert("Route niet gevonden");
return;
}
if(result.response.route) {
// Pick the first route from the response:
route = result.response.route[0];
// Pick the route's shape:
routeShape = route.shape;
// Create a linestring to use as a point source for the route line
linestring = new H.geo.LineString();
// Push all the points in the shape into the linestring:
routeShape.forEach(function(point) {
var parts = point.split(',');
linestring.pushLatLngAlt(parts[0], parts[1]);
});
// Retrieve the mapped positions of the requested waypoints:
startPoint = route.waypoint[0].mappedPosition;
endPoint = route.waypoint[1].mappedPosition;
// Create a polyline to display the route:
var routeLine = new H.map.Polyline(linestring, {
style: { strokeColor: 'blue', lineWidth: 5 },
arrows: { fillColor: 'white', frequency: 5, width: 1, length: 1 }
});
// Create a marker for the start point:
var startMarker = new H.map.Marker({
lat: startPoint.latitude,
lng: startPoint.longitude
});
// Create a marker for the end point:
var endMarker = new H.map.Marker({
lat: endPoint.latitude,
lng: endPoint.longitude
});
// Add the route polyline and the two markers to the map:
map.addObjects([routeLine, startMarker, endMarker]);
// Set the map's viewport to make the whole route visible:
map.setViewBounds(routeLine.getBounds());
addWaypointsToPanel(route.waypoint);
addManueversToPanel(route);
addSummaryToPanel(route.summary);
document.getElementById("distance").value = route.summary.distance;
//alert(route.summary.distance);
//alert(route.summary)
// toonAfstand(route.summary);
}
};
// END CALLBACK FUNCTIONS
// functie aanroepen om taal naar het Nederlands te zetten
switchMapLanguage(map , platform);
switch(typeaction){
case 'showadres': {
if (formatadres == "latlng") {
var reverseGeocodingParams = {
// prox: '51.20866,3.18413',
prox: fromadres,
mode: 'retrieveAddresses',
maxresults: 1
};
geocoder.reverseGeocode(reverseGeocodingParams, onShowlatlong, function(e) {
alert(e);
});
}
else {
var geocodingParams = {
searchText: fromadres
};
// Call the geocode method with the geocoding parameters,
// the callback and an error callback function (called if a
// communication error occurs):
geocoder.geocode(geocodingParams, onShowadress, function(e) {
alert(e);
});
}
break;
};
case 'showpin': {
var adressMarker = new H.map.Marker({
lat: fromlatitude,
lng: fromlongitude
});
// Add the route polyline and the two markers to the map:
map.addObjects([adressMarker]);
map.setCenter({lat: fromlatitude, lng: fromlongitude});
map.setZoom(17);
break;
}
// mode=shortest;car;traffic:disabled
case 'calcroutelatlng': {
var fromlatlng = 'geo!' + fromlatitude + ',' + fromlongitude;
var tolatlng = 'geo!' + tolatitude + ',' + tolongitude;
var routingParameters = {
// The routing mode:
mode: routemode,
// The start point of the route:
waypoint0: fromlatlng,
// The end point of the route:
waypoint1: tolatlng,
// To retrieve the shape of the route we choose the route
representation: 'display',
routeattributes : 'waypoints,summary,shape,legs',
maneuverattributes: 'direction,action',
language: 'nl-nl'
};
router.calculateRoute(routingParameters, onCalcRoutelatlng,
function(error) {
alert(error.message);
});
break;
}
};
// functie om map in het nederlands te krijgen, dit wordt aangeroepen bij het laden van de map
function switchMapLanguage(map, platform){
var mapTileService = platform.getMapTileService({type: 'base'}),
// Our layer will load tiles from the HERE Map Tile API
dutchMapLayer = mapTileService.createTileLayer(
'maptile',
'normal.day',
512,
'png8',
{lg: 'DUT'}
);
map.setBaseLayer(dutchMapLayer);
ui.removeControl('mapsettings');
}
function readUrlParameters (urlParameters) {
// split up the query string and store in an
// associative array
var urlParameters = urlParameters.split("&");
var queryStringList = {};
for(var i=0;i<urlParameters.length;i++)
{
var tmp = urlParameters[i].split("=");
queryStringList[tmp[0]] = unescape(tmp[1]);
}
appid = queryStringList["appid"];
appcode = queryStringList["appcode"];
typeaction = queryStringList["action"];
formatadres = queryStringList["formatadres"];
fromadres = queryStringList["adress1"];
minrelevance = queryStringList["minrelevance"];
fromlatitude = queryStringList["fromlat"];
fromlongitude = queryStringList["fromlng"];
tolatitude = queryStringList["tolat"];
tolongitude = queryStringList["tolng"];
routemode = queryStringList["routemode"];
}
function addWaypointsToPanel (waypoints){
var nodeH3 = document.createElement('h5'),
waypointLabels = [],
i;
nodeH3.style.marginLeft = '1%';
for (i = 0; i < waypoints.length; i += 1) {
waypointLabels.push(waypoints[i].label)
}
nodeH3.textContent = waypointLabels.join(' - ');
routeInstructionsContainer.innerHTML = '';
routeInstructionsContainer.appendChild(nodeH3);
}
function addManueversToPanel(route){
var nodeOL = document.createElement('ol'),
i,
j;
nodeOL.style.fontSize = 'small';
nodeOL.style.marginLeft ='2%';
nodeOL.style.marginRight ='2%';
nodeOL.className = 'directions';
// Add a marker for each maneuver
for (i = 0; i < route.leg.length; i += 1) {
for (j = 0; j < route.leg[i].maneuver.length; j += 1) {
// Get the next maneuver.
maneuver = route.leg[i].maneuver[j];
var li = document.createElement('li'),
// spanArrow = document.createElement('span'),
spanInstruction = document.createElement('span');
// spanArrow.className = 'arrow ' + maneuver.action;
spanInstruction.innerHTML = maneuver.instruction;
//li.appendChild(spanArrow);
li.appendChild(spanInstruction);
nodeOL.appendChild(li);
}
}
routeInstructionsContainer.appendChild(nodeOL);
}
function addSummaryToPanel(summary){
var summaryDiv = document.createElement('div'),
content = '';
content += '<b>Totale afstand</b>: ' + (summary.distance / 1000) + 'km. <br/>';
content += '<b>Reistijd</b>: ' + summary.travelTime.toMMSS() + ' (huidig verkeer)';
summaryDiv.style.fontSize = 'small';
summaryDiv.style.marginLeft ='2%';
summaryDiv.style.marginRight ='2%';
summaryDiv.innerHTML = content;
routeInstructionsContainer.appendChild(summaryDiv);
}
</script>
<form method="post">
<input name="fromLatitudechar" id="fromLatitudechar" type="hidden">
<input name="fromLongitudechar" id="fromLongitudechar" type="hidden">
<input name="toLatitudechar" id="toLatitudechar" type="hidden">
<input name="toLongitudechar" id="toLongitudechar" type="hidden">
<input name="fromRelevance" id="fromRelevance" type="hidden">
<input name="toRelevance" id="toRelevance" type="hidden">
<input name="distance" id="distance" type="hidden">
</form>
</body>
</html>
We checked the routing result between two addresses with route api.
And there is a restriction to turn left from Steenweg to Hertstraat. The location lat long is 50.906072,4.054588.
We will check the restriction whether exit or not in real world and update it.
Thank you!

Google maps API, waypoints, stopover true/false option give different results when using departureTime for specific open(summer)/closed(winter) roads

When following Google API Directions i ran into a problem. I cannot find a solution to get this working correctly. Seems like it has to be a google issue.
If you check the images and snippet example you can see between waypoint A end B there is a road that is only open during summertime. During wintertime closed and gets a longer route which is normal.
When stopover is set to FALSE (during summertime) then the route is correct but there are no legs anymore. I need those legs between the waypoints. When triple checking the google API i cannot find why this behavior occurs. I'm aware some things are not working with TRANSIT but this is not the case here.
So i need the SHORT summer route with stopovers and with leg information as result. Any ideas to get this?
Image: stopover=false
Image: stopover=true
When switching between stopover mode change 2 vars at line 36-37
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3";></script>
<script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var wptruefalse;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var first = new google.maps.LatLng(61.84448683734486, 8.85223388671875);
var second = new google.maps.LatLng(61.75298123367897, 9.078826904296875);
var start = new google.maps.LatLng(61.484039,7.645798);
var end = new google.maps.LatLng(61.944118091023746,7.97882080078125);
var request = {
origin: start,
destination: end,
waypoints: [{location: first, stopover: wptruefalse},
{location: second, stopover: wptruefalse}],
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
drivingOptions: {
departureTime: new Date("08/08/2018")
},
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById("directions_panel");
summaryPanel.innerHTML = "";
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
summaryPanel.innerHTML += route.legs[i].start_address + " to ";
summaryPanel.innerHTML += route.legs[i].end_address + "<br />";
summaryPanel.innerHTML += route.legs[i].distance.text + "<br /><br />";
}
} else {
alert("directions response " + status);
}
});
}
function doClick(myRadio) {
if (myRadio.value === "true") {
wptruefalse = true;
} else {
wptruefalse = false;
}
calcRoute();
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="float:left;width:70%;height:100%;"></div>
<div id="control_panel" style="float:right;width:30%;text-align:left;padding-top:20px">
API Key is needed to test properly
<form>
<input type="radio" name="wpradio" onclick="doClick(this);" value="true" checked> True
<input type="radio" name="wpradio" onclick="doClick(this);" value="false"> False
</form>
<div id="directions_panel" style="margin:20px;background-color:#FFEE77;"></div>
</div>
</body>
</html>
Thanks in advance!

How to to Get Places (e.g Gas Stations) along Route Between Origin and Destination in Google Maps API

Can you please let me know if it is possible to get list of all places for example Gas Stations along Route Between Origin and Destination in Google Maps API? Here is a link that I am trying to list all Gas Stations or Rest areas ( or any of Google Maps API Supported Place Types)between two points ans based on a Direction supported route.
and this my code so far:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var haight = new google.maps.LatLng(49.216364,-122.811897);
var oceanBeach = new google.maps.LatLng(50.131446,-119.506838);
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();
}
function calcRoute() {
var request = {
origin: haight,
destination: oceanBeach,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Edited Part:
// Make the directions request
directionService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsRenderer.setDirections(result);
// Box around the overview path of the first route
var path = result.routes[0].overview_path;
var boxes = routeBoxer.box(path, distance);
drawBoxes(boxes);
} else {
alert("Directions query failed: " + status);
}
for (var i = 0; i < boxes.length; i++) {
var bounds = box[i];
// Perform search over this bounds
}
});
}
Use the RouteBoxer to get an array of google.maps.LatLngBounds objects that cover the route.
for each of those bounds use the Places library to search for the places.
Note that there are query limits and quotas on the places requests, so for long routes this may not be practical.
example
(however, looking at how the results are grouped, it looks like the places service is searching around the center of the bounds, rather than in the bounds, but it might be good enough for your needs).
code snippet:
var map = null;
var boxpolys = null;
var directions = null;
var routeBoxer = null;
var distance = null; // km
var service = null;
var gmarkers = [];
var boxes = null;
var infowindow = new google.maps.InfoWindow();
function initialize() {
// Default the map view to the continental U.S.
var mapOptions = {
center: new google.maps.LatLng(40, -80.5),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 8
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
service = new google.maps.places.PlacesService(map);
routeBoxer = new RouteBoxer();
directionService = new google.maps.DirectionsService();
directionsRenderer = new google.maps.DirectionsRenderer({
map: map
});
// If there are any parameters at eh end of the URL, they will be in location.search
// looking something like "?marker=3"
// skip the first character, we are not interested in the "?"
var query = location.search.substring(1);
// split the rest at each "&" character to give a list of "argname=value" pairs
var pairs = query.split("&");
for (var i = 0; i < pairs.length; i++) {
// break each pair at the first "=" to obtain the argname and value
var pos = pairs[i].indexOf("=");
var argname = pairs[i].substring(0, pos).toLowerCase();
var value = pairs[i].substring(pos + 1).toLowerCase();
// process each possible argname - use unescape() if theres any chance of spaces
if (argname == "to") {
document.getElementById('to').value = unescape(value);
}
if (argname == "from") {
document.getElementById('from').value = unescape(value);
}
if (argname == "dist") {
document.getElementById('distance').value = parseFloat(value);
}
if (argname == "type") {
document.getElementById('type').value = unescape(value);
}
if (argname == "keyword") {
document.getElementById('keyword').value = unescape(value);
}
if (argname == "name") {
document.getElementById('name').value = unescape(value);
}
if (argname == "submit") {
route();
}
}
}
function route() {
// Clear any previous route boxes from the map
clearBoxes();
// Convert the distance to box around the route from miles to km
distance = parseFloat(document.getElementById("distance").value) * 1.609344;
var request = {
origin: document.getElementById("from").value,
destination: document.getElementById("to").value,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
// Make the directions request
directionService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsRenderer.setDirections(result);
// Box around the overview path of the first route
var path = result.routes[0].overview_path;
boxes = routeBoxer.box(path, distance);
// alert(boxes.length);
drawBoxes();
findPlaces(0);
} else {
alert("Directions query failed: " + status);
}
});
}
// Draw the array of boxes as polylines on the map
function drawBoxes() {
boxpolys = new Array(boxes.length);
for (var i = 0; i < boxes.length; i++) {
boxpolys[i] = new google.maps.Rectangle({
bounds: boxes[i],
fillOpacity: 0,
strokeOpacity: 1.0,
strokeColor: '#000000',
strokeWeight: 1,
map: map
});
}
}
function findPlaces(searchIndex) {
var type = document.getElementById('type').value;
var keyword = document.getElementById('keyword').value;
var name = document.getElementById('name').value;
var request = {
bounds: boxes[searchIndex],
};
if (!!type && (type != "")) {
if (type.indexOf(',') > 0)
request.types = type.split(',');
else
request.types = [type];
}
if (!!keyword && (keyword != "")) request.keyword = keyword;
if (!!name && (name != "")) request.name = name;
service.nearbySearch(request, function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
document.getElementById('side_bar').innerHTML += "bounds[" + searchIndex + "] returns " + results.length + " results<br>"
for (var i = 0, result; result = results[i]; i++) {
var marker = createMarker(result);
}
} else {
document.getElementById('side_bar').innerHTML += "bounds[" + searchIndex + "] returns 0 results<br> status=" + status + "<br>";
}
if (status != google.maps.places.PlacesServiceStatus.OVER_QUERY_LIMIT) {
searchIndex++;
if (searchIndex < boxes.length)
findPlaces(searchIndex);
} else { // delay 1 second and try again
setTimeout("findPlaces(" + searchIndex + ")", 1000);
}
});
}
// Clear boxes currently on the map
function clearBoxes() {
if (boxpolys != null) {
for (var i = 0; i < boxpolys.length; i++) {
boxpolys[i].setMap(null);
}
}
boxpolys = null;
}
function createMarker(place) {
var placeLoc = place.geometry.location;
if (place.icon) {
var image = new google.maps.MarkerImage(
place.icon, new google.maps.Size(71, 71),
new google.maps.Point(0, 0), new google.maps.Point(17, 34),
new google.maps.Size(25, 25));
} else var image = {
url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
size: new google.maps.Size(7, 7),
anchor: new google.maps.Point(3.5, 3.5)
};
var marker = new google.maps.Marker({
map: map,
icon: image,
position: place.geometry.location
});
var request = {
reference: place.reference
};
google.maps.event.addListener(marker, 'click', function() {
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var contentStr = '<h5>' + place.name + '</h5><p>' + place.formatted_address;
if (!!place.formatted_phone_number) contentStr += '<br>' + place.formatted_phone_number;
if (!!place.website) contentStr += '<br><a target="_blank" href="' + place.website + '">' + place.website + '</a>';
contentStr += '<br>' + place.types + '</p>';
infowindow.setContent(contentStr);
infowindow.open(map, marker);
} else {
var contentStr = "<h5>No Result, status=" + status + "</h5>";
infowindow.setContent(contentStr);
infowindow.open(map, marker);
}
});
});
gmarkers.push(marker);
if (!place.name) place.name = "result " + gmarkers.length;
var side_bar_html = "<a href='javascript:google.maps.event.trigger(gmarkers[" + parseInt(gmarkers.length - 1) + "],\"click\");'>" + place.name + "</a><br>";
document.getElementById('side_bar').innerHTML += side_bar_html;
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
margin: 0;
padding: 0;
height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://cdn.jsdelivr.net/gh/denissellu/routeboxer#master/src/RouteBoxer.js" type="text/javascript"></script>
<table border="1">
<tr>
<td valign="top">
<div id="map" style="width: 600px; height: 500px;"></div>
</td>
<td>
<div id="side_bar" style="width:200px; height: 600px; overflow: auto"></div>
</td>
</tr>
</table>
Box within at least
<input type="text" id="distance" value="3" size="2">miles of the route from
<input type="text" id="from" value="denver" />to
<input type="text" id="to" value="oklahoma city, OK" />
<input type="submit" onclick="route()" />
<br>
<label>type</label>
<input type="text" id="type" value="gas_station" />
<label>keyword</label>
<input type="text" id="keyword" value="" />
<label>name</label>
<input type="text" id="name" value="" />
<div id="towns"></div>

How to find places along the route using google map api? [duplicate]

Can you please let me know if it is possible to get list of all places for example Gas Stations along Route Between Origin and Destination in Google Maps API? Here is a link that I am trying to list all Gas Stations or Rest areas ( or any of Google Maps API Supported Place Types)between two points ans based on a Direction supported route.
and this my code so far:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var haight = new google.maps.LatLng(49.216364,-122.811897);
var oceanBeach = new google.maps.LatLng(50.131446,-119.506838);
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();
}
function calcRoute() {
var request = {
origin: haight,
destination: oceanBeach,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Edited Part:
// Make the directions request
directionService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsRenderer.setDirections(result);
// Box around the overview path of the first route
var path = result.routes[0].overview_path;
var boxes = routeBoxer.box(path, distance);
drawBoxes(boxes);
} else {
alert("Directions query failed: " + status);
}
for (var i = 0; i < boxes.length; i++) {
var bounds = box[i];
// Perform search over this bounds
}
});
}
Use the RouteBoxer to get an array of google.maps.LatLngBounds objects that cover the route.
for each of those bounds use the Places library to search for the places.
Note that there are query limits and quotas on the places requests, so for long routes this may not be practical.
example
(however, looking at how the results are grouped, it looks like the places service is searching around the center of the bounds, rather than in the bounds, but it might be good enough for your needs).
code snippet:
var map = null;
var boxpolys = null;
var directions = null;
var routeBoxer = null;
var distance = null; // km
var service = null;
var gmarkers = [];
var boxes = null;
var infowindow = new google.maps.InfoWindow();
function initialize() {
// Default the map view to the continental U.S.
var mapOptions = {
center: new google.maps.LatLng(40, -80.5),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 8
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
service = new google.maps.places.PlacesService(map);
routeBoxer = new RouteBoxer();
directionService = new google.maps.DirectionsService();
directionsRenderer = new google.maps.DirectionsRenderer({
map: map
});
// If there are any parameters at eh end of the URL, they will be in location.search
// looking something like "?marker=3"
// skip the first character, we are not interested in the "?"
var query = location.search.substring(1);
// split the rest at each "&" character to give a list of "argname=value" pairs
var pairs = query.split("&");
for (var i = 0; i < pairs.length; i++) {
// break each pair at the first "=" to obtain the argname and value
var pos = pairs[i].indexOf("=");
var argname = pairs[i].substring(0, pos).toLowerCase();
var value = pairs[i].substring(pos + 1).toLowerCase();
// process each possible argname - use unescape() if theres any chance of spaces
if (argname == "to") {
document.getElementById('to').value = unescape(value);
}
if (argname == "from") {
document.getElementById('from').value = unescape(value);
}
if (argname == "dist") {
document.getElementById('distance').value = parseFloat(value);
}
if (argname == "type") {
document.getElementById('type').value = unescape(value);
}
if (argname == "keyword") {
document.getElementById('keyword').value = unescape(value);
}
if (argname == "name") {
document.getElementById('name').value = unescape(value);
}
if (argname == "submit") {
route();
}
}
}
function route() {
// Clear any previous route boxes from the map
clearBoxes();
// Convert the distance to box around the route from miles to km
distance = parseFloat(document.getElementById("distance").value) * 1.609344;
var request = {
origin: document.getElementById("from").value,
destination: document.getElementById("to").value,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
// Make the directions request
directionService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsRenderer.setDirections(result);
// Box around the overview path of the first route
var path = result.routes[0].overview_path;
boxes = routeBoxer.box(path, distance);
// alert(boxes.length);
drawBoxes();
findPlaces(0);
} else {
alert("Directions query failed: " + status);
}
});
}
// Draw the array of boxes as polylines on the map
function drawBoxes() {
boxpolys = new Array(boxes.length);
for (var i = 0; i < boxes.length; i++) {
boxpolys[i] = new google.maps.Rectangle({
bounds: boxes[i],
fillOpacity: 0,
strokeOpacity: 1.0,
strokeColor: '#000000',
strokeWeight: 1,
map: map
});
}
}
function findPlaces(searchIndex) {
var type = document.getElementById('type').value;
var keyword = document.getElementById('keyword').value;
var name = document.getElementById('name').value;
var request = {
bounds: boxes[searchIndex],
};
if (!!type && (type != "")) {
if (type.indexOf(',') > 0)
request.types = type.split(',');
else
request.types = [type];
}
if (!!keyword && (keyword != "")) request.keyword = keyword;
if (!!name && (name != "")) request.name = name;
service.nearbySearch(request, function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
document.getElementById('side_bar').innerHTML += "bounds[" + searchIndex + "] returns " + results.length + " results<br>"
for (var i = 0, result; result = results[i]; i++) {
var marker = createMarker(result);
}
} else {
document.getElementById('side_bar').innerHTML += "bounds[" + searchIndex + "] returns 0 results<br> status=" + status + "<br>";
}
if (status != google.maps.places.PlacesServiceStatus.OVER_QUERY_LIMIT) {
searchIndex++;
if (searchIndex < boxes.length)
findPlaces(searchIndex);
} else { // delay 1 second and try again
setTimeout("findPlaces(" + searchIndex + ")", 1000);
}
});
}
// Clear boxes currently on the map
function clearBoxes() {
if (boxpolys != null) {
for (var i = 0; i < boxpolys.length; i++) {
boxpolys[i].setMap(null);
}
}
boxpolys = null;
}
function createMarker(place) {
var placeLoc = place.geometry.location;
if (place.icon) {
var image = new google.maps.MarkerImage(
place.icon, new google.maps.Size(71, 71),
new google.maps.Point(0, 0), new google.maps.Point(17, 34),
new google.maps.Size(25, 25));
} else var image = {
url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
size: new google.maps.Size(7, 7),
anchor: new google.maps.Point(3.5, 3.5)
};
var marker = new google.maps.Marker({
map: map,
icon: image,
position: place.geometry.location
});
var request = {
reference: place.reference
};
google.maps.event.addListener(marker, 'click', function() {
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var contentStr = '<h5>' + place.name + '</h5><p>' + place.formatted_address;
if (!!place.formatted_phone_number) contentStr += '<br>' + place.formatted_phone_number;
if (!!place.website) contentStr += '<br><a target="_blank" href="' + place.website + '">' + place.website + '</a>';
contentStr += '<br>' + place.types + '</p>';
infowindow.setContent(contentStr);
infowindow.open(map, marker);
} else {
var contentStr = "<h5>No Result, status=" + status + "</h5>";
infowindow.setContent(contentStr);
infowindow.open(map, marker);
}
});
});
gmarkers.push(marker);
if (!place.name) place.name = "result " + gmarkers.length;
var side_bar_html = "<a href='javascript:google.maps.event.trigger(gmarkers[" + parseInt(gmarkers.length - 1) + "],\"click\");'>" + place.name + "</a><br>";
document.getElementById('side_bar').innerHTML += side_bar_html;
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
margin: 0;
padding: 0;
height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://cdn.jsdelivr.net/gh/denissellu/routeboxer#master/src/RouteBoxer.js" type="text/javascript"></script>
<table border="1">
<tr>
<td valign="top">
<div id="map" style="width: 600px; height: 500px;"></div>
</td>
<td>
<div id="side_bar" style="width:200px; height: 600px; overflow: auto"></div>
</td>
</tr>
</table>
Box within at least
<input type="text" id="distance" value="3" size="2">miles of the route from
<input type="text" id="from" value="denver" />to
<input type="text" id="to" value="oklahoma city, OK" />
<input type="submit" onclick="route()" />
<br>
<label>type</label>
<input type="text" id="type" value="gas_station" />
<label>keyword</label>
<input type="text" id="keyword" value="" />
<label>name</label>
<input type="text" id="name" value="" />
<div id="towns"></div>

Google place Api PlaceDetails

Hi the below code gives the place search , but it is showing only names i want the complete details of the places in the infobox..the below code isprovided by DR.Molle
http://jsfiddle.net/doktormolle/C5ZtK/
below is the code for retrieving the placedetails but not able to make it working
var request = { reference: place.reference };
service.getDetails(request, function(details, status) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(details.name + "<br />" + details.formatted_address +"<br />" + details.website + "<br />" + details.rating + "<br />" + details.formatted_phone_number);
infowindow.open(map, this);
});
});
}
i checked the developers page but not able to get much from it Any help would be appreciated
Example that gets the place details for the clicked marker:
http://www.geocodezip.com/v3_GoogleEx_place-search_starbucks3.html
code snippet:
var geocoder = null;
var map;
var service;
var infowindow;
var gmarkers = [];
var bounds = null;
function initialize() {
geocoder = new google.maps.Geocoder();
var pyrmont = new google.maps.LatLng(-33.8665433, 151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 15
});
geocoder.geocode({
'address': "Seattle, WA"
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var point = results[0].geometry.location;
bounds = results[0].geometry.viewport;
var rectangle = new google.maps.Rectangle({
bounds: bounds,
fillColor: "#FF0000",
fillOpacity: 0.4,
strokeColor: "#0000FF",
strokeWeigth: 2,
strokeOpacity: 0.9,
map: map
});
map.fitBounds(bounds);
var request = {
bounds: bounds,
name: "starbucks",
types: ['establishment']
};
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.search(request, callback);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
var request = {
reference: place.reference
};
google.maps.event.addListener(marker, 'click', function() {
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var contentStr = '<h5>' + place.name + '</h5><p>' + place.formatted_address;
if (!!place.formatted_phone_number) contentStr += '<br>' + place.formatted_phone_number;
if (!!place.website) contentStr += '<br><a target="_blank" href="' + place.website + '">' + place.website + '</a>';
contentStr += '<br>' + place.types + '</p>';
infowindow.setContent(contentStr);
infowindow.open(map, marker);
}
});
});
gmarkers.push(marker);
var side_bar_html = "<a href='javascript:google.maps.event.trigger(gmarkers[" + parseInt(gmarkers.length - 1) + "],\"click\");'>" + place.name + "</a><br>";
document.getElementById('side_bar').innerHTML += side_bar_html;
}
function openInfoWindow(id) {
return true;
}
google.maps.event.addDomListener(window, 'load', initialize);
#map {
height: 400px;
width: 600px;
border: 1px solid #333;
margin-top: 0.6em;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<table border="1">
<tr>
<td>
<div id="map"></div>
</td>
<td>
<div id="side_bar"></div>
</td>
</tr>
</table>

Resources