Pedestrian and bicycle route longer then car route - here-api

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!

Related

Wordpress Plugin for Google Maps: How to return the Map

I have a PHP Site which takes Data from XML File to display Markers on a Google Maps. When I navigate direct to the page, everything is working. To integrate that code on my Wordpress Page, I thought about writing a plugin for that:
<? defined('ABSPATH') or die("Thanks for visting");
function showMap() { ?>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<div id="map"></div>
<script>
var customLabel = {
Location: {
label: 'L'
},
Brautaustatter: {
label: 'B'
},
Herrenausstatter: {
label: 'H'
},
Florist: {
label: 'F'
},
Konditor: {
label: 'K'
},
Sonstiges: {
label: 'S'
}
};
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(48.2048, 16.375),
zoom: 12
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP or XML file
downloadUrl('showXML.php', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var id = markerElem.getAttribute('id');
var name = markerElem.getAttribute('location');
var address = markerElem.getAttribute('address');
var type = markerElem.getAttribute('type');
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customLabel[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
label: icon.label
});
marker.addListener('click', function() {
infoWindow.setContent(infowincontent);
infoWindow.open(map, marker);
});
});
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap">
</script>
<? add_shortcode( 'show_google_maps', 'showMap' ); ?>
<? } ?>
Now I do not know how to return the whole map with the markers? How can I solve this? Do I have to create a "main" function where all the other functions are nested? Is that what I want to achieve possible with that piece of code? Thanks for any advice!
BR,
Stefan

Problems Getting XML data with custom icon to show in Google Map on my site

Hello all I am trying to resolve an issue with getting my XML data to show in a map. I am still learning the code, but perhaps someone could help me determine why the icons / data will not show.
Here is a sample of my XML:
<?xml version="1.0"?>
<markers>
<marker
id="461"
name="Pilot Travel Center"
address="I-20 / 59, Exit 123"
city="Birmingham"
state="AL"
zip="35204"
phone="xxx-xxx-xxxx"
fax="xxx-xxx-xxxx"
manager="Joe"
lat="33.529307"
lng="-86.852215"
url="http://www.pilotflyingj.com"
type="restaurant"/>
<marker
id="1402"
name="Flying J Travel Plaza"
address="Ross Clark Highway / Highway 231"
city="Dothan"
state="AL"
zip="36301"
phone="xxx-xxx-xxxx"
fax="xxx-xxx-xxxx"
manager="Johnny"
lat="31.192005"
lng="-85.399838"
url="http://www.pilotflyingj.com"
type="restaurant"/>
</markers>
and here is the google API portion
<script>
var customIcons = {
restaurant: {
icon: 'ts_images/cat_scales.png',
},
bar: {
icon: 'ts_images/xx.png',
}
};
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(39.809734, -98.555620),
zoom: 4
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP or XML file
downloadUrl('xml/cat_scales.xml', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var id = markerElem.getAttribute('id');
var name = markerElem.getAttribute('name');
var address = markerElem.getAttribute('address');
var city = markerElem.getAttribute('city');
var state = markerElem.getAttribute('state');
var zip = markerElem.getAttribute('zip');
var phone = markerElem.getAttribute('phone');
var fax = markerElem.getAttribute('fax');
var manager = markerElem.getAttribute('manager');
var url = markerElem.getAttribute('url');
var phone = markerElem.getAttribute('phone');
var type = markerElem.getAttribute('type');
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
marker.addListener('click', function() {
infoWindow.setContent(infowincontent);
infoWindow.open(map, marker);
});
});
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
I have searched but cannot determine what the issue is. I would greatly appreciate the help. Thank You.
Use the full URL of the custom icons. It needs to be a complete URL publicly available on the web (pointing to your webserver where you have your custom icon).
for example (using icons on my server):
http://www.geocodezip.com/mapIcons/marker_red.png
So define the custom icon structure like this:
var customIcons = {
restaurant: {
icon: 'http://www.geocodezip.com/mapIcons/marker_red.png',
},
bar: {
icon: 'http://www.geocodezip.com/mapIcons/marker_blue.png',
}
};
proof of concept fiddle
code snippet:
var customIcons = {
restaurant: {
icon: 'http://www.geocodezip.com/mapIcons/marker_red.png',
},
bar: {
icon: 'http://www.geocodezip.com/mapIcons/marker_blue.png',
}
};
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(39.809734, -98.555620),
zoom: 4
});
var infoWindow = new google.maps.InfoWindow();
// Change this depending on the name of your PHP or XML file
// downloadUrl('xml/cat_scales.xml', function(data) {
// var xml = data.responseXML;
var xml = xmlParse(xmlStr);
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var id = markerElem.getAttribute('id');
var name = markerElem.getAttribute('name');
var address = markerElem.getAttribute('address');
var city = markerElem.getAttribute('city');
var state = markerElem.getAttribute('state');
var zip = markerElem.getAttribute('zip');
var phone = markerElem.getAttribute('phone');
var fax = markerElem.getAttribute('fax');
var manager = markerElem.getAttribute('manager');
var url = markerElem.getAttribute('url');
var type = markerElem.getAttribute('type');
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
marker.addListener('click', function() {
infoWindow.setContent(infowincontent);
infoWindow.open(map, marker);
});
});
// });
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
google.maps.event.addDomListener(window, 'load', initMap);
function xmlParse(str) {
if ((typeof ActiveXObject != 'undefined') || ("ActiveXObject" in window)) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
}
if (typeof DOMParser != 'undefined') {
return (new DOMParser()).parseFromString(str, 'text/xml');
}
return document.createElement('div', null);
}
var xmlStr = '<?xml version="1.0"?><markers><marker id="461" name="Pilot Travel Center" address="I-20 / 59, Exit 123" city="Birmingham" state="AL" zip="35204" phone="xxx-xxx-xxxx" fax="xxx-xxx-xxxx" manager="Joe" lat="33.529307" lng="-86.852215" url="http://www.pilotflyingj.com" type="restaurant"/><marker id="1402" name="Flying J Travel Plaza" address="Ross Clark Highway / Highway 231" city="Dothan" state="AL" zip="36301" phone="xxx-xxx-xxxx" fax="xxx-xxx-xxxx" manager="Johnny" lat="31.192005" lng="-85.399838" url="http://www.pilotflyingj.com" type="bar"/></markers>';
html,
body,
#map {
height: 100%;
width: 100%;
padding: 0px;
margin: 0px;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id='map'></div>

How to draw different coloured polylines with direction service with snap to road feature

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't get Google Maps api v3 to display markers from xml file

I should have on my hands what is proper working JS and an xml file...I'm simply trying to take advantage of the huge database of locations that has been offered up as free for everyone to use - located # http://www.craftbeer.com/breweries/brewery-locator/find-a-us-brewery
I'm tried using their maps.js and xml file...but all I end up with is a blank maps screen...
Here is the Javascript...
/*********************************************
**Google Maps Custom API work**
This code can be reused on any site to display a local map of breweries from our local iMis dump, as well as pull in beermapping.
Hey! Don't forget to include API in functions.php! Function is conditionally initialized in footer.php
*/
//Set up variables to create marker
var gmarkers = [];
var mapMarkers = [];
var geocoder = new google.maps.Geocoder();
var icon = 'http://www.craftbeer.com/wp-content/uploads/marker.png';
//Initialize Map
function view_map(xml_file, latitude, longitude, varZoom) {
console.log('view map');
map = new google.maps.Map(document.getElementById("map_canvas"), { //Create the map, Set Default Zoom level and type
center: new google.maps.LatLng(latitude, longitude),
zoom: varZoom,
mapTypeId: 'roadmap',
panControl: true,
zoomControl: true,
mapTypeControl: false,
scaleControl: true,
streetViewControl: false,
overviewMapControl: false
});
//-- Listeners --//
google.maps.event.addListener(map, 'center_changed', function() {
console.log('center changed');
//clearMarkers();
});
google.maps.event.addListenerOnce(map, 'tilesloaded', function(){
//this part runs when the mapobject is created and rendered
console.log("loaded");
$("#loading-screen").fadeOut(250, function(){});
$("#loading-icon").fadeOut();
//google.maps.event.addListenerOnce(map, 'tilesloaded', function(){ });
});
//console.log(xml_file);
var download_file = xml_file; //this variable is passed in so we can re-use this script
//Pull in the XML feed
downloadUrl(download_file, function(data) {
console.log("downloading xml");
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
//Loop through all markers in the XML file
for (var i = 0; i < markers.length; i++) {
var state = markers[i].getAttribute("state");
var x = markers[i].getAttribute("lat");
var y = markers[i].getAttribute("lng");
if ( state != 'PR' && state != 'VI' && state != 'GU' && x != "" ){
//console.log(state);
var ids = parseFloat(markers[i].getAttribute("id"));
var z = new google.maps.LatLng(x,y,i);
//console.log(x);
var _id = markers[i].getAttribute("id");
var name = markers[i].getAttribute("company");
var address = markers[i].getAttribute("address");
var city = markers[i].getAttribute("city");
var zip = markers[i].getAttribute("zip");
var phone = markers[i].getAttribute("phone");
var url = markers[i].getAttribute("url");
var brewery_type = markers[i].getAttribute("type");
var member_type = '';
var member_type = markers[i].getAttribute("member_type");
var offer = markers[i].getAttribute("offer");
var html = "<div class='bubble_content'><strong>" + name + "</strong><br />";
html += address + "<br/>" + city + ", " + state + " " + zip;
if(url) html += "<br /><br /><a href='http://" + url + "' target='_blank'>Visit Web Site</a></div>";
//var marker = createMarker(ids, z, title, contentstring);
var marker = new google.maps.Marker({
position: z,
map: map,
title: name,
icon: icon,
html: html,
zindex: i
});
//Add a listener for every icon click
google.maps.event.addListener(marker,'click',function(){
infowindow.setContent(this.html);
infowindow.open(map,this);
//map.setZoom(10);
//map.setCenter(this.getPosition());
console.log(this);
});
gmarkers[ids] = marker;
mapMarkers.push(marker);
if( x && y ){
//console.log(ids);
var infowindow = new google.maps.InfoWindow({content: html});
}
/* google.maps.event.addListener(marker, 'click', function() {
console.log('marker clicked');
});
*/
//bounds.extend(z);
//map.fitBounds(bounds);
}//end check for US states only!
} //end for loop
var mcOptions = {gridSize: 60, maxZoom: 9};
var markerCluster = new MarkerClusterer(map, mapMarkers, mcOptions); //this is the function that groups the icons into markers
});
} //End full function to create map
/*
* FUNCTION
*
* click to bring up one icon when clicked from the list.
*/
function myclick(i){
console.log('clicked a title ' + i);
smoothScroll("#primary");
var lat = parseFloat(gmarkers[i].position.k);
var lng = parseFloat(gmarkers[i].position.B);
console.log(lat);
map.setCenter({lat: lat, lng: lng});
map.setZoom(13);
google.maps.event.trigger(gmarkers[i], 'click');
};
function createMarker(ids, z, title, contentstring){
console.log('createMarker');
var marker = new google.maps.Marker({
position: z,
map: map,
title: title,
html: contentstring,
icon: 'http://maps.google.com/mapfiles/ms/icons/orange-dot.png'
});
google.maps.event.addListener(marker,'click',function(){
infowindow.setContent(this.html);
infowindow.open(map,marker);
});
gmarkers[ids] = marker;
//console.log(gmarkers[ids]);
};
/*
* FUNCTION findAddress()
*
* given an adress string, zoom the map to the proper state
*/
function findAddress(position) {
//Let's determind if we have a state (address) or LatLng
var addressStr = $("#state_select li.active").data('state-id');
if (addressStr != 'Select a State') address = "US State of "+addressStr;
if(position) {
var lat = parseFloat(position['latitude']);
var lng = parseFloat(position['longitude']);
var latlng = new google.maps.LatLng(lat, lng);
//console.log(latlng);
}
//Now let's geocode - two different cases
if (geocoder && position) { //If LatLng
//console.log('near me');
geocoder.geocode( { 'location': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
if (results && results[0] && results[0].geometry && results[0].geometry.viewport && addressStr!="ON" && addressStr!="INT") {
map.fitBounds(results[0].geometry.viewport); //resize map to fit.
map.setZoom(13);
}
} else {
alert("No results found");
}
}
});
} else if (geocoder && address!="") { //If State
//console.log('by state');
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
if (results && results[0] && results[0].geometry && results[0].geometry.viewport && addressStr!="ON" && addressStr!="INT") {
map.fitBounds(results[0].geometry.viewport); //resize map to fit.
map.setZoom(6);
}
} else {
alert("No results found");
}
}
});
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
And here is the link to the xml file....
http://www.straighttothepint.com/wp-content/uploads/wp-google-maps/Google_Map_APIs.xml
I've spent days doing google searches and testing different sections of code to at least get a basic google map to show up via the xml file markers...but to no avail - Any help would be tremendously appreciated!!
~Cheers
EDIT:
Everything worked as expected once I included the following script inline on the page prior to calling the maps.js file. Thanks everyone!
<script>
$(document).ready(function(){
var latitude = 39.300299;
var longitude = -97.382812;
view_map('./uploads/your_xml_file.xml', latitude,longitude,4);
//scripts to handle mapping are in js/mylibs/map.js.php
});
</script>
Looking at the html and the code you provided above I constructed a fiddle for you:
http://jsfiddle.net/loanburger/qafsex5x/
I added two markers in an xml string at the top in the fiddle.
I basically parse the xml doing this:
var markers = $(xml).find("marker");
Its then simply the same for loop you had:
for (var i = 0; i < markers.length; i++)
{
...
}
The fiddle will show you the markers.

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>

Resources