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

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>

Related

Google Maps is showing blank using API 3 and autosuggestion is not working

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 /////////////////

markers places are incorrect in KML google map

I made a map on Google Maps, I downloaded the KML file and used it in a map with sidebar. But the places of the markers are incorrect. All of them are below the correct places. The code is as below. Example page is on test page .If I use the simple KML layer example of Google, same errors occur.
<style type="text/css">
html, body, #map_canvas {
width: 750px;
height: 600px;
margin: 0;
padding: 0;
}
.infowindow * {font-size: 90%; margin: 0}
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/branches/polys/geoxml3.js">
</script>
<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/trunk/ProjectedOverlay.js">
</script>
<script type="text/javascript">
var geoXml = null;
var geoXmlDoc = null;
var map = null;
var myLatLng = null;
var myGeoXml3Zoom = true;
var sidebarHtml = "";
var infowindow = null;
var kmlLayer = null;
var filename = "europeancapitals.xml";
function MapTypeId2UrlValue(maptype) {
var urlValue = 'm';
switch(maptype){
case google.maps.MapTypeId.HYBRID: urlValue='h';
break;
case google.maps.MapTypeId.SATELLITE: urlValue='k';
break;
case google.maps.MapTypeId.TERRAIN: urlValue='t';
break;
default:
case google.maps.MapTypeId.ROADMAP: urlValue='m';
break;
}
return urlValue;
}
// ========== This function will create the "link to this page"
function makeLink() {
// var a="http://www.geocodezip.com/v3_MW_example_linktothis.html"
var url = window.location.pathname;
var a = url.substring(url.lastIndexOf('/')+1)
+ "?lat=" + map.getCenter().lat().toFixed(6)
+ "&lng=" + map.getCenter().lng().toFixed(6)
+ "&zoom=" + map.getZoom()
+ "&type=" + MapTypeId2UrlValue(map.getMapTypeId());
if (filename != "europeancapitals.xml") a += "&filename="+filename;
document.getElementById("link").innerHTML = '<a href="' +a+ '">Link to this page<\/a>';
}
function initialize() {
myLatLng = new google.maps.LatLng(46,14);
// these set the initial center, zoom and maptype for the map
// if it is not specified in the query string
var lat = 46;
var lng = 14;
var zoom = 8;
var maptype = google.maps.MapTypeId.ROADMAP;
// 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 == "id") {id = unescape(value);}
if (argname == "filename") {filename = unescape(value);}
if (argname == "marker") {index = parseFloat(value);}
if (argname == "lat") {lat = parseFloat(value);}
if (argname == "lng") {lng = parseFloat(value);}
if (argname == "zoom") {
zoom = parseInt(value);
myGeoXml3Zoom = false;
}
if (argname == "type") {
// from the v3 documentation 8/24/2010
// HYBRID This map type displays a transparent layer of major streets on satellite images.
// ROADMAP This map type displays a normal street map.
// SATELLITE This map type displays satellite images.
// TERRAIN This map type displays maps with physical features such as terrain and vegetation.
if (value == "m") {maptype = google.maps.MapTypeId.ROADMAP;}
if (value == "k") {maptype = google.maps.MapTypeId.SATELLITE;}
if (value == "h") {maptype = google.maps.MapTypeId.HYBRID;}
if (value == "t") {maptype = google.maps.MapTypeId.TERRAIN;}
}
}
if (!isNaN(lat) && !isNaN(lng)) {
myLatLng = new google.maps.LatLng(lat, lng);
}
var myOptions = {
zoom: zoom,
center: myLatLng,
// zoom: 5,
// center: myLatlng,
mapTypeId: maptype
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
infowindow = new google.maps.InfoWindow({});
geoXml = new geoXML3.parser({
map: map,
infoWindow: infowindow,
singleInfoWindow: true,
zoom: myGeoXml3Zoom,
markerOptions: {optimized: false},
afterParse: useTheData
});
geoXml.parse(filename);
google.maps.event.addListener(map, "bounds_changed", makeSidebar);
google.maps.event.addListener(map, "center_changed", makeSidebar);
google.maps.event.addListener(map, "zoom_changed", makeSidebar);
// Make the link the first time when the page opens
makeLink();
// Make the link again whenever the map changes
google.maps.event.addListener(map, 'maptypeid_changed', makeLink);
google.maps.event.addListener(map, 'center_changed', makeLink);
google.maps.event.addListener(map, 'bounds_changed', makeLink);
google.maps.event.addListener(map, 'zoom_changed', makeLink);
};
function kmlPgClick(pm) {
if (geoXml.docs[0].placemarks[pm].polygon.getMap()) {
google.maps.event.trigger(geoXmlDoc.placemarks[pm].polygon,"click");
} else {
geoXmlDoc.placemarks[pm].polygon.setMap(map);
google.maps.event.trigger(geoXmlDoc.placemarks[pm].polygon,"click");
}
}
function kmlPlClick(pm) {
if (geoXml.docs[0].placemarks[pm].polyline.getMap()) {
google.maps.event.trigger(geoXmlDoc.placemarks[pm].polyline,"click");
} else {
geoXmlDoc.placemarks[pm].polyline.setMap(map);
google.maps.event.trigger(geoXmlDoc.placemarks[pm].polyline,"click");
}
}
function kmlClick(pm) {
if (geoXml.docs[0].placemarks[pm].marker.getMap()) {
google.maps.event.trigger(geoXml.docs[0].placemarks[pm].marker,"click");
} else {
geoXmlDoc.placemarks[pm].marker.setMap(map);
google.maps.event.trigger(geoXmlDoc.placemarks[pm].marker,"click");
}
}
function kmlShowPlacemark(pm) {
if (geoXmlDoc.placemarks[pm].polygon) {
map.fitBounds(geoXmlDoc.placemarks[pm].polygon.bounds);
} else if (geoXmlDoc.placemarks[pm].polyline) {
map.fitBounds(geoXmlDoc.placemarks[pm].polyline.bounds);
} else if (geoXmlDoc.placemarks[pm].marker) {
map.setCenter(geoXmlDoc.placemarks[pm].marker.getPosition());
}
for (var i=0;i<geoXmlDoc.placemarks.length;i++) {
var placemark = geoXmlDoc.placemarks[i];
if (i == pm) {
if (placemark.polygon) placemark.polygon.setMap(map);
if (placemark.polyline) placemark.polyline.setMap(map);
if (placemark.marker) placemark.marker.setMap(map);
} else {
if (placemark.polygon) placemark.polygon.setMap(null);
if (placemark.polyline) placemark.polyline.setMap(null);
if (placemark.marker) placemark.marker.setMap(null);
}
}
}
var highlightOptions = {fillColor: "#FFFF00", strokeColor: "#000000", fillOpacity: 0.9, strokeWidth: 10};
var highlightLineOptions = {strokeColor: "#FFFF00", strokeWidth: 10};
function kmlHighlightPoly(pm) {
for (var i=0;i<geoXmlDoc.placemarks.length;i++) {
var placemark = geoXmlDoc.placemarks[i];
if (i == pm) {
if (placemark.polygon) placemark.polygon.setOptions(highlightOptions);
if (placemark.polyline) placemark.polyline.setOptions(highlightLineOptions);
} else {
if (placemark.polygon) placemark.polygon.setOptions(placemark.polygon.normalStyle);
if (placemark.polyline) placemark.polyline.setOptions(placemark.polyline.normalStyle);
}
}
}
function kmlUnHighlightPoly(pm) {
for (var i=0;i<geoXmlDoc.placemarks.length;i++) {
if (i == pm) {
var placemark = geoXmlDoc.placemarks[i];
if (placemark.polygon) placemark.polygon.setOptions(placemark.polygon.normalStyle);
if (placemark.polyline) placemark.polyline.setOptions(placemark.polyline.normalStyle);
}
}
}
function showAll() {
map.fitBounds(geoXmlDoc.bounds);
for (var i=0;i<geoXmlDoc.placemarks.length;i++) {
var placemark = geoXmlDoc.placemarks[i];
if (placemark.polygon) placemark.polygon.setMap(map);
if (placemark.polyline) placemark.polyline.setMap(map);
if (placemark.marker) placemark.marker.setMap(map);
}
}
function highlightPoly(poly, polynum) {
// poly.setOptions({fillColor: "#0000FF", strokeColor: "#0000FF", fillOpacity: 0.3}) ;
google.maps.event.addListener(poly,"mouseover",function() {
var rowElem = document.getElementById('row'+polynum);
if (rowElem) rowElem.style.backgroundColor = "#FFFA5E";
if (geoXmlDoc.placemarks[polynum].polygon) {
poly.setOptions(highlightOptions);
} else if (geoXmlDoc.placemarks[polynum].polyline) {
poly.setOptions(highlightLineOptions);
}
});
google.maps.event.addListener(poly,"mouseout",function() {
var rowElem = document.getElementById('row'+polynum);
if (rowElem) rowElem.style.backgroundColor = "#FFFFFF";
poly.setOptions(poly.normalStyle);
});
}
// == rebuilds the sidebar to match the markers currently displayed ==
function makeSidebarPolygonEntry(i) {
var name = geoXmlDoc.placemarks[i].name;
if (!name || (name.length == 0)) name = "polygon #"+i;
// alert(name);
sidebarHtml += '<tr id="row'+i+'"><td onmouseover="kmlHighlightPoly('+i+');" onmouseout="kmlUnHighlightPoly('+i+');">'+name+' - show</td></tr>';
}
function makeSidebarPolylineEntry(i) {
var name = geoXmlDoc.placemarks[i].name;
if (!name || (name.length == 0)) name = "polyline #"+i;
// alert(name);
sidebarHtml += '<tr id="row'+i+'"><td onmouseover="kmlHighlightPoly('+i+');" onmouseout="kmlUnHighlightPoly('+i+');">'+name+' - show</td></tr>';
}
function makeSidebarEntry(i) {
var name = geoXmlDoc.placemarks[i].name;
if (!name || (name.length == 0)) name = "marker #"+i;
// alert(name);
sidebarHtml += '<tr id="row'+i+'"><td>'+name+'</td></tr>';
}
function makeSidebar() {
sidebarHtml = '<table><tr><td>Show All</td></tr>';
var currentBounds = map.getBounds();
// if bounds not yet available, just use the empty bounds object;
if (!currentBounds) currentBounds=new google.maps.LatLngBounds();
if (geoXmlDoc) {
for (var i=0; i<geoXmlDoc.placemarks.length; i++) {
if (geoXmlDoc.placemarks[i].polygon) {
if (currentBounds.intersects(geoXmlDoc.placemarks[i].polygon.bounds)) {
makeSidebarPolygonEntry(i);
}
}
if (geoXmlDoc.placemarks[i].polyline) {
if (currentBounds.intersects(geoXmlDoc.placemarks[i].polyline.bounds)) {
makeSidebarPolylineEntry(i);
}
}
if (geoXmlDoc.placemarks[i].marker) {
if (currentBounds.contains(geoXmlDoc.placemarks[i].marker.getPosition())) {
makeSidebarEntry(i);
}
}
}
}
sidebarHtml += "</table>";
document.getElementById("sidebar").innerHTML = sidebarHtml;
}
function useTheData(doc){
var currentBounds = map.getBounds();
if (!currentBounds) currentBounds=new google.maps.LatLngBounds();
// Geodata handling goes here, using JSON properties of the doc object
sidebarHtml = '<table><tr><td>Show All</td></tr>';
// var sidebarHtml = '<table>';
geoXmlDoc = doc[0];
for (var i = 0; i < geoXmlDoc.placemarks.length; i++) {
// console.log(doc[0].markers[i].title);
var placemark = geoXmlDoc.placemarks[i];
if (placemark.polygon) {
if (currentBounds.intersects(placemark.polygon.bounds)) {
makeSidebarPolygonEntry(i);
}
var normalStyle = {
strokeColor: placemark.polygon.get('strokeColor'),
strokeWeight: placemark.polygon.get('strokeWeight'),
strokeOpacity: placemark.polygon.get('strokeOpacity'),
fillColor: placemark.polygon.get('fillColor'),
fillOpacity: placemark.polygon.get('fillOpacity')
};
placemark.polygon.normalStyle = normalStyle;
highlightPoly(placemark.polygon, i);
}
if (placemark.polyline) {
if (currentBounds.intersects(placemark.polyline.bounds)) {
makeSidebarPolylineEntry(i);
}
var normalStyle = {
strokeColor: placemark.polyline.get('strokeColor'),
strokeWeight: placemark.polyline.get('strokeWeight'),
strokeOpacity: placemark.polyline.get('strokeOpacity')
};
placemark.polyline.normalStyle = normalStyle;
highlightPoly(placemark.polyline, i);
}
if (placemark.marker) {
if (currentBounds.contains(placemark.marker.getPosition())) {
makeSidebarEntry(i);
}
}
/* doc[0].markers[i].setVisible(false); */
}
sidebarHtml += "</table>";
document.getElementById("sidebar").innerHTML = sidebarHtml;
};
function hide_kml(){
geoXml.hideDocument();
}
function unhide_kml(){
geoXml.showDocument();
}
function reload_kml(){
geoXml.hideDocument();
delete geoXml;
geoXml = new geoXML3.parser({
map: map,
singleInfoWindow: true,
afterParse: useTheData
});
geoXml.parse(filename);
}
function hide_markers_kml(){
for (var i=0;i<geoXmlDoc.markers.length;i++) {
geoXmlDoc.markers[i].setVisible(false);
}
}
function unhide_markers_kml(){
for (var i=0;i<geoXmlDoc.markers.length;i++) {
geoXmlDoc.markers[i].setVisible(true);
}
}
function hide_polys_kml(){
for (var i=0;i<geoXmlDoc.gpolylines.length;i++) {
geoXmlDoc.gpolylines[i].setMap(null);
}
}
function unhide_polys_kml(){
for (var i=0;i<geoXmlDoc.gpolylines.length;i++) {
geoXmlDoc.gpolylines[i].setMap(map);
}
}
function load_kmlLayer() {
kmlLayer = new google.maps.KmlLayer(filename);
google.maps.event.addListener(kmlLayer, "status_changed", function() {
document.getElementById('kmlstatus').innerHTML = "Kml Status:"+kmlLayer.getStatus();
});
kmlLayer.setMap(map);
}
function hide_kmlLayer() {
kmlLayer.setMap(null);
}
function show_kmlLayer() {
kmlLayer.setMap(map);
}
</script>
</head>
<body onload="initialize()">
<h4>Reading a KML file with Google Maps JavaScript API Version 3 and geoxml3.</h4>
<!-- <button onclick="hide_polys_kml();">hide polylines</button>
<button onclick="unhide_polys_kml();">unhide polylines</button> -->
<button onclick="hide_kml();">hide</button>
<button onclick="unhide_kml();">unhide</button>
<button onclick="hide_markers_kml();">hide markers</button>
<button onclick="unhide_markers_kml();">show markers</button>
<button onclick="load_kmlLayer();">load kmlLayer</button>
<button onclick="hide_kmlLayer();">hide kmlLayer</button>
<button onclick="show_kmlLayer();">show kmlLayer</button>
<!-- <button onclick="reload_kml();">reload</button> -->
<table style="width:100%;"><tr><td>
<div id="map_canvas">
</div>
</td><td>
<div id="sidebar" style="width:300px;height:600px; overflow:auto"></div>
</td></tr>
<tr><td colspan="2"> <div id="link"></div></td></tr>
</table>
<div id="map_text">
</div>
<div id="kmlstatus"></div>
</body>
</html>
You need to set the "hotSpot" for your custom icons.
<hotSpot x="0.5" y="0.5" xunits="fraction" yunits="fraction">
Specifies the position within the Icon that is "anchored" to the specified in the Placemark. The x and y
values can be specified in three different ways: as pixels ("pixels"), as fractions of the icon ("fraction"), or as
inset pixels ("insetPixels"), which is an offset in pixels from the upper right corner of the icon. The x and y
positions can be specified in different ways—for example, x can be in pixels and y can be a fraction. The origin of > the coordinate system is in the lower left corner of the icon.
The hotSpot tag is (now) supported (correctly) in the kmz branch of geoxml3:
working example

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>

Google Maps DistanceMatrix

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>

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