I am using Google API, what I need to do is get two different distances in miles. At the moment I have the following:-
var start = arrObjLatLngs[0];
var end = arrObjLatLngs[arrObjLatLngs.length - 1];
var base = new google.maps.LatLng(52.781048888889, -1.2110222222222546);
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [base, base],
destinations: [start, end],
travelMode: google.maps.TravelMode.DRIVING,
avoidHighways: false,
avoidTolls: false
}, callback);
function callback(response, status) {
if (status == google.maps.DistanceMatrixStatus.OK) {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var element = results[j];
var distance = element.distance.text;
var duration = element.duration.text;
var from = origins[i];
var to = destinations[j];
}
}
}
}
What I need to have is two variables; $runinPickup and $runinDestination that contains the distance between 1.) base and start (which will be $runinPickup) and 2.) base and end (which will be $runinDestination)
If I alert distance I get the response:-
13.9 km
5.2 km
13.9 km
5.2 km
Firstly, I'm just wanting to know how I can get the distance of just the distance between base and start as $runinPickup. Secondly, is there a way I can do this so it doesn't include the decimal? So instead of 13.9 km for the first value, it would just be 13.
Then I would need to convert it into miles, which I'm guessing once I can get the value I would do it as follows:
var pickup_distance = parseInt(($fieldPickup / 8) * 5); ?
Any help would be much appreciated! :)
Did you read the documentation? Passing the same address twice in the origins array:
origins: [base, base],
destinations: [start, end],
Is going to give you the same result twice. This should work (not tested), and give you 2 results:
origins: [base],
destinations: [start, end],
To get miles I would suggest setting the unitSystem to IMPERIAL (although I can't find a definition of what that means in the documentation):
unitSystem (optional) — The unit system to use when displaying distance. Accepted values are:
google.maps.UnitSystem.METRIC (default)
google.maps.UnitSystem.IMPERIAL
You can of course convert METRIC units to miles.
Example showing the two values, with distances in IMPERIAL units. Modified from the example in the documentation.
code snippet:
var map;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];
var base = new google.maps.LatLng(55.930385, -3.118425);
var start = 'Greenwich, England';
var destinationA = 'Stockholm, Sweden';
var end = new google.maps.LatLng(50.087692, 14.421150);
var destinationIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';
function initialize() {
var opts = {
center: new google.maps.LatLng(55.53, 9.4),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), opts);
geocoder = new google.maps.Geocoder();
calculateDistances();
}
google.maps.event.addDomListener(window, 'load', initialize);
function calculateDistances() {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [base],
destinations: [start, end],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('outputDiv');
outputDiv.innerHTML = '<table border="1">';
deleteOverlays();
var stringArray = ['$runinPickup', '$runinDestination'];
var htmlString = '<table border="1">';
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
addMarker(origins[i], false);
for (var j = 0; j < results.length; j++) {
addMarker(destinations[j], true);
htmlString += '<tr><td>' + stringArray[j] + '</td><td>' + results[j].distance.text + '</td></tr>';
outputDiv.innerHTML += '<tr><td>' + stringArray[j] + '</td><td>' + results[j].distance.text + '</td></tr>';
}
}
htmlString += '</table>';
// outputDiv.innerHTML += '</table>';
outputDiv.innerHTML = htmlString;
// alert(htmlString);
}
}
function addMarker(location, isDestination) {
var icon;
if (isDestination) {
icon = destinationIcon;
} else {
icon = originIcon;
}
geocoder.geocode({
'address': location
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: icon
});
markersArray.push(marker);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
body {
margin: 20px;
font-family: courier, sans-serif;
font-size: 12px;
}
#map {
height: 480px;
width: 640px;
border: solid thin #333;
margin-top: 20px;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="outputDiv"></div>
<div id="map"></div>
Related
I'm trying to provide a direction service using WordPress.
And the API using here is APi but the map is only displaying blank and also when address is entered, it didn't return any result.
I bought a plugin from CodeCanyon but it's no longer supported.
This is the call I made:
wp_enqueue_style('jqmap-style-ui-slide', WP_PLUGIN_URL . '/JQMap_RouteCalc/css/jquery-ui-1.8.17.custom.css');
wp_register_script('jquery-JQMap_RouteCalcgoogleapis', 'https://maps.googleapis.com/maps/api/js?key=MY-KEY-HERE-kQ&libraries=places');
wp_enqueue_script('jquery-JQMap_RouteCalc',WP_PLUGIN_URL . '/JQMap_RouteCalc/js/jquery-JQMap_RouteCalc.js', array('jquery','jquery-ui-slider','jquery-JQMap_RouteCalcgoogleapis'));
And this is the JavaScript below
(function($){
//////////////////////// FUNCTION TO GIVE AUTOCOMPLETE TO EACH CALC INPUTS //////////////
function autocomplete_map(container){
container.find("input").each(function(){
new google.maps.places.Autocomplete($(this)[0]);
$(this).attr('placeholder','')
});
}
////////////////////////// FUNCTION TO PRIN ROUTE INFO ///////////
function print_route(panel){
var a = window.open('','','width=300,height=300');
a.document.open("text/html");
a.document.write(panel.html());
a.document.close();
a.print();
}
////////////////////////// START GOOGLE MAP API /////////////////
var myOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
, geocoder = new google.maps.Geocoder();
function center(imap,iaddress,info_window,zoom){
var map;
map = new google.maps.Map(imap, {
zoom: zoom,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var address = iaddress;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
if(info_window != ''){
var infowindow = new google.maps.InfoWindow({
content: info_window
});
infowindow.open(map,marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
setTimeout(function(){$('.map_container').find('img').css({'max-width':'none','max-height':'none'});},500);
}
function initialize(imap,ipanel,start,end,wp,travel_mode_select,opt_wp,printable_panel,DivContainerDistance) {
var directionsDisplay = new google.maps.DirectionsRenderer({draggable: true})
, directionsService = new google.maps.DirectionsService()
, oldDirections = []
, currentDirections;
map = new google.maps.Map(imap, myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(ipanel);
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
if (currentDirections) {
oldDirections.push(currentDirections);
}
currentDirections = directionsDisplay.getDirections();
computeTotalDistance(directionsDisplay.directions,DivContainerDistance);
});
var waypts = []
, dest = wp
, request = {
origin: start,
destination: end,
waypoints:waypts,
optimizeWaypoints:opt_wp,
travelMode: google.maps.DirectionsTravelMode[travel_mode_select]
};
for (var i = 0; i < dest.length; i++) {
if (dest[i].value != "") {
waypts.push({
location:dest[i].value,
stopover:true});
}
}
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
printable_panel.html('')
var route = response.routes[0];
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
printable_panel.append("<b>Route Segment: " + routeSegment + "</b><br />"
+route.legs[i].start_address + " to "+route.legs[i].end_address + "<br />"
+route.legs[i].distance.text + "<br /><br />");
}
}
if ( status != 'OK' ){ alert(status); return false;}
setTimeout(function(){$('.map_container').find('img').css({'max-width':'none','max-height':'none'});},500);
});
setTimeout(function(){$('.map_container').find('img').css({'max-width':'none','max-height':'none'});},500);
}
function computeTotalDistance(result,DivContainerDistance) {
var total = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000.
$(DivContainerDistance).html('Total Distance: '+total + " km")
}
////////////////////////// END GOOGLE MAP API /////////////////
I'm getting incorrect country codes when using Google Places API to geocode point locations. This happens mainly near country borders so I suppose that Places API is using a different source for country borders (with less precision) than the one shown in the Google Map tiles.
In the example below, the point is clearly inside France but the returned ISO code by Google Places is "ES" for "Spain".
function initMap() {
var geocoder = new google.maps.Geocoder;
var point = new google.maps.LatLng(42.4241355,2.2915667);
var map = new google.maps.Map(document.getElementById('map'), { zoom: 16, center: point });
var country_name = "Undefined";
geocoder.geocode({'location': point}, function(results, status, country_name) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
for (var i=0; i < results[0].address_components.length; i++) {
for (var j=0; j < results[0].address_components[i].types.length; j++) {
if (results[0].address_components[i].types[j] == "country") {
country = results[0].address_components[i];
}
}
}
country_name = country.short_name;
} else {
country_name = "Geocoder no results found";
}
} else {
country_name = 'Geocoder failed due to: ' + status;
}
var marker = new google.maps.Marker({ position: point, map: map });
var infowindow = new google.maps.InfoWindow({ content: country_name });
infowindow.open(map, marker);
});
}
#map { height: 400px; width: 100%; }
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyABsURr0TnnANUUgsqN_Rk2VXhqgZfZrEk&callback=initMap"> </script>
The location of the reverse geocoded result that you are using is on the other side of the border.
(BTW - this is the Google Reverse Geocoder, not the Google Places API)
proof of concept fiddle
blue marker in image below is location of reverse geocoded result
code snippet:
function initMap() {
var geocoder = new google.maps.Geocoder;
var point = new google.maps.LatLng(42.4241355, 2.2915667);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: point
});
var country_name = "Undefined";
var bounds = new google.maps.LatLngBounds();
bounds.extend(point);
geocoder.geocode({
'location': point
}, function(results, status, country_name) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[0]) {
for (var i = 0; i < results[0].address_components.length; i++) {
for (var j = 0; j < results[0].address_components[i].types.length; j++) {
if (results[0].address_components[i].types[j] == "country") {
country = results[0].address_components[i];
console.log("country=" + country.short_name + ":" + country.long_name + " i=" + i + " j=" + j);
console.log("results=" + JSON.stringify(results));
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
icon: "http://maps.google.com/mapfiles/ms/micons/blue.png"
});
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
}
}
}
country_name = country.short_name;
} else {
country_name = "Geocoder no results found";
}
} else {
country_name = 'Geocoder failed due to: ' + status;
}
var marker = new google.maps.Marker({
position: point,
map: map
});
var infowindow = new google.maps.InfoWindow({
content: country_name
});
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, "load", initMap);
#map {
height: 400px;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
I am trying to render bus routes of bangalore city with snap to road feature provided by google api. If I just render single route, it is visible with the colour I mention for stroke color property of polyline.If the route is pretty long, then I am splitting the route into multiple paths for that route. But, when I add the second route, a polyline from the end of first route to the start of second route is drawn. I am not able to figure out, where I am going wrong. Any help is deeply appreciated. Please find the javascript code of the same.
<script type="text/javascript">
var infoWindow = new google.maps.InfoWindow();
var routePath;
var OrgDest;
var OrgDestpoints;
var wp;
var waypts;
var traceroutePath;
var service;
var map;
var marker, markloc;
var markers = [];
var orgdest = {"1": [[12.9197565816171, 77.5923588994416,12.95719452, 77.56829549],[12.95719452, 77.56829549,12.98997477, 77.57209867],[12.98997477, 77.57209867,13.02311, 77.55029]],"KHC": [[12.97466107, 77.58199613,12.97466107, 77.58199613]]};
var waypoints = {"1":[[12.92268932, 77.59338455,12.92318598, 77.58877168,12.9279596, 77.58760419,12.93610683, 77.58392363,12.93672057, 77.57217014,12.93956243, 77.57215225,12.94189, 77.57358,12.94574241, 77.57070059],[12.95850855, 77.57402561,12.96161187, 77.57527904,12.96366, 77.56843,12.96811874, 77.56800682,12.97736, 77.57074,12.98997477, 77.57209867],[12.98997477, 77.57209867,12.99789013, 77.57130999,13.00908169, 77.5710476,13.01742075, 77.55707759]],"KHC": [[12.98420536, 77.59761828,12.98368012, 77.6035693]]};
var routeColors = {"1": "#FF00FF","KHC": "#800000"};
var routeNames = ["1","KHC"];
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(12.9536775, 77.5883784),
zoom: 12
};
map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);
//directionsDisplay.setMap(map);
var routeInfoWindow = new google.maps.InfoWindow({ // this info window shows the route name when the mouse hovers over a route line
disableAutoPan: true
});
for (var i = 0; i < routeNames.length; i++) { // loop over each route
var routeName = routeNames[i];
for (var j = 0; j < orgdest[routeName].length; j++) { // loop over each path on the route
OrgDest = orgdest[routeName][j];
OrgDestpoints = []
for (var k = 0; k < OrgDest.length; k += 2) { // loop over each point in the path
OrgDestpoints.push(new google.maps.LatLng(OrgDest[k], OrgDest[k+1]));
}
waypts = [];
if(waypoints[routeName].length > 0)
{
wp = waypoints[routeName][j];
for (var k = 0; k < wp.length; k += 2) { // loop over each waypoints in the path
waypts.push(
{location:new google.maps.LatLng(wp[k], wp[k+1]),
stopover:true
});
}
}
if(j>0)// & (j!=(orgdest[routeName].length)))
traceroutePath.setMap(null); //clearing previously rendered map
if(i>0 & j==0)
{
traceroutePath.setMap(null); //clearing previously rendered map
}
routePath = OrgDestpoints;
traceroutePath = new google.maps.Polyline({
path: routePath,
strokeColor: routeColors[routeName],
strokeOpacity: 1.0,
strokeWeight: 2
});
service = new google.maps.DirectionsService(),traceroutePath,snap_path=[];
traceroutePath.setMap(map);
for(z=0;z<routePath.length-1;z++){
service.route({origin: routePath[z],destination: routePath[z+1],
travelMode: google.maps.DirectionsTravelMode.DRIVING,
waypoints: waypts},
function(result, status) {
if(status == google.maps.DirectionsStatus.OK) {
snap_path = snap_path.concat(result.routes[0].overview_path);
alert(result.routes[0].legs[0].start_location)
traceroutePath.setPath(snap_path);
} else alert("Directions request failed: "+status);
});
}
} //end of j for loop; paths to form a route
}//end of i for loop; all routes
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
You have two issues that are causing the issue.
the code is concatenating the paths from the directions requests together, that is an issue because:
a. the directions service is asynchronous, the routes may come back in a different order than you send them (unless you send them one by one).
b. the routes requested are not continuous.
for (z = 0; z < routePath.length - 1; z++) {
service.route({
origin: routePath[z],
destination: routePath[z + 1],
travelMode: google.maps.DirectionsTravelMode.DRIVING,
waypoints: waypts
},
function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
var snap_path = result.routes[0].overview_path;
var traceroutePath = new google.maps.Polyline({
strokeColor: routeColors[routeName],
strokeOpacity: 1.0,
strokeWeight: 2,
map: map
});
traceroutePath.setPath(snap_path);
} else alert("Directions request failed: " + status);
});
proof of concept fiddle
code snippet:
var infoWindow = new google.maps.InfoWindow();
var routePath;
var OrgDest;
var OrgDestpoints;
var wp;
var waypts;
var traceroutePath;
var service;
var map;
var marker, markloc;
var markers = [];
var orgdest = {
"1": [
[12.9197565816171, 77.5923588994416, 12.95719452, 77.56829549],
[12.95719452, 77.56829549, 12.98997477, 77.57209867],
[12.98997477, 77.57209867, 13.02311, 77.55029]
],
"KHC": [
[12.97466107, 77.58199613, 12.97466107, 77.58199613]
]
};
var waypoints = {
"1": [
[12.92268932, 77.59338455, 12.92318598, 77.58877168, 12.9279596, 77.58760419, 12.93610683, 77.58392363, 12.93672057, 77.57217014, 12.93956243, 77.57215225, 12.94189, 77.57358, 12.94574241, 77.57070059],
[12.95850855, 77.57402561, 12.96161187, 77.57527904, 12.96366, 77.56843, 12.96811874, 77.56800682, 12.97736, 77.57074, 12.98997477, 77.57209867],
[12.98997477, 77.57209867, 12.99789013, 77.57130999, 13.00908169, 77.5710476, 13.01742075, 77.55707759]
],
"KHC": [
[12.98420536, 77.59761828, 12.98368012, 77.6035693]
]
};
var routeColors = {
"1": "#FF00FF",
"KHC": "#800000"
};
var routeNames = ["1", "KHC"];
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(12.9536775, 77.5883784),
zoom: 12
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var routeInfoWindow = new google.maps.InfoWindow({ // this info window shows the route name when the mouse hovers over a route line
disableAutoPan: true
});
for (var i = 0; i < routeNames.length; i++) { // loop over each route
var routeName = routeNames[i];
for (var j = 0; j < orgdest[routeName].length; j++) { // loop over each path on the route
OrgDest = orgdest[routeName][j];
OrgDestpoints = []
for (var k = 0; k < OrgDest.length; k += 2) { // loop over each point in the path
OrgDestpoints.push(new google.maps.LatLng(OrgDest[k], OrgDest[k + 1]));
}
waypts = [];
if (waypoints[routeName].length > 0) {
wp = waypoints[routeName][j];
for (var k = 0; k < wp.length; k += 2) { // loop over each waypoints in the path
waypts.push({
location: new google.maps.LatLng(wp[k], wp[k + 1]),
stopover: true
});
}
}
if (j > 0) // & (j!=(orgdest[routeName].length)))
traceroutePath.setMap(null); //clearing previously rendered map
if (i > 0 & j == 0) {
traceroutePath.setMap(null); //clearing previously rendered map
}
routePath = OrgDestpoints;
traceroutePath = new google.maps.Polyline({
path: routePath,
strokeColor: routeColors[routeName],
strokeOpacity: 1.0,
strokeWeight: 2
});
service = new google.maps.DirectionsService(), traceroutePath, snap_path = [];
traceroutePath.setMap(map);
for (z = 0; z < routePath.length - 1; z++) {
service.route({
origin: routePath[z],
destination: routePath[z + 1],
travelMode: google.maps.DirectionsTravelMode.DRIVING,
waypoints: waypts
},
function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
var snap_path = result.routes[0].overview_path;
var traceroutePath = new google.maps.Polyline({
strokeColor: routeColors[routeName],
strokeOpacity: 1.0,
strokeWeight: 2,
map: map
});
traceroutePath.setPath(snap_path);
} else alert("Directions request failed: " + status);
});
}
} //end of j for loop; paths to form a route
} //end of i for loop; all routes
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>
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>
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>