I'm getting "Permission Denied" all the time when I'm trying to fetch my location with this code:
function initialize() {
$('.map-fullsize').hide();
$('#weather-map').hide();
$('#weather-data').hide();
if(geo_position_js.init()) {
var waiting_time = $('#getting-position').html('Försöker att hitta din aktuella position. Var god vänta...');
t = setTimeout(function() {
waiting_time.html('Det tar längre tid att hitta din position, än vad det egentligen borde göra.<br><br><b>Tips</b><br>GPS-mottagaren har lättare att hitta dig om du är utomhus. Täta moln som till exempel vid ett åskoväder, kan göra det svårare för satelliterna att hämta din position.');
}, 60000);
geo_position_js.getCurrentPosition(show_position, function() {
clearTimeout(t);
$('#getting-position').html('<b>Ett fel uppstod</b><br>Din position kunde inte hittas. Se till att vara utomhus för bästa möjliga resultat och försök igen.');
}, {
enableHighAccuracy: true
});
} else {
$('#getting-position').html('<b>Ett fel uppstod</b><br>Det verkar som att din webbläsare inte tillåter GPS-positionering.');
}
}
function show_position(p) {
$('.map-fullsize').show();
$('#weather-map').show();
$('#weather-data').show();
$('#getting-position').hide();
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showError, function(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var accuracy = position.coords.accuracy;
var speed = position.coords.speed;
var altitude = position.coords.altitude;
var heading = position.coords.heading;
var coords = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
center: coords,
streetViewControl: false,
mapTypeControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL,
position: google.maps.ControlPosition.TOP_LEFT
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(
document.getElementById('weather-map'), mapOptions
);
var marker = new google.maps.Marker({
position: coords,
map: map
});
var circle = new google.maps.Circle({
center: coords,
radius: accuracy,
map: map,
fillColor: '#3333ff',
fillOpacity: 0.4,
strokeColor: '#3333ff',
strokeOpacity: 0.8,
strokeWeight: 1
});
map.setCenter(coords);
if(accuracy > 30) {
map.fitBounds(circle.getBounds());
} else {
map.setZoom(14);
}
$('#weather-data').load('jquery-fetch/fetch-weatherdata.php?coor=' + latitude.toFixed(6).replace(/\./, '') + ',' + longitude.toFixed(6).replace(/\./, '') + '&coordinates=' + latitude.toFixed(6) + ',' + longitude.toFixed(6) + '&accuracy=' + accuracy + '&speed=' + speed + '&altitude=' + altitude + '&heading=' + heading);
});
} else {
alert('Geolocation API stöds inte i din webbläsare');
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
$('.map-fullsize').hide();
$('#weather-map').hide();
$('#weather-data').hide();
$('#permission-denied').show();
break;
case error.POSITION_UNAVAILABLE:
$('.map-fullsize').hide();
$('#weather-map').hide();
$('#weather-data').hide();
$('#position-unavailable').show();
break;
case error.TIMEOUT:
$('.map-fullsize').hide();
$('#weather-map').hide();
$('#weather-data').hide();
$('#timeout').show();
break;
case error.UNKNOWN_ERROR:
$('.map-fullsize').hide();
$('#weather-map').hide();
$('#weather-data').hide();
$('#unknown-error').show();
break;
}
}
}
$(document).ready(function() {
initialize();
});
I can't find anything wrong with this code and the funny thing with this is that the code is getting my GPS location before I'm getting "Permission Denied". This problem is an "follow-up" to my previous question. How can I fix my problem?
Thanks in advance.
You are using
navigator.geolocation.getCurrentPosition(showError, function(position) {...})
The specification for getCurrentPosition shows the functions in the other order. The reason for this is that only the success callback is mandatory; it must come first. If a second argument is supplied, it's the error callback. A third argument is an options object.
just two things;
i) to test this I simplified your code a little, fixed some small problems and removed the dependancy on geo.js.
ii) The geolocation will only work when the site is hosted on an external http:// server
<html>
<body>
<div id='map' class='map-fullsize'></div>
<div id='weather-map'></div>
<div id='weather-data'></div>
<div id='getting-position'></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type='text/javascript'>
function initialize() {
$('.map-fullsize').hide();
$('#weather-map').hide();
$('#weather-data').hide();
var waiting_time = $('#getting-position').html('Försöker att hitta din aktuella position. Var god vänta...');
get_position();
t = setTimeout(function () {
$('#getting-position').html('Det tar längre tid att hitta din position, än vad det egentligen borde göra.<br><br><b>Tips</b><br>GPS-mottagaren har lättare att hitta dig om du är utomhus. Täta moln som till exempel vid ett åskoväder, kan göra det svårare för satelliterna att hämta din position.');
}, 60000);
}
function get_position() {
$('#getting-position').html("get_position()");
$('.map-fullsize').show();
$('#weather-map').show();
$('#weather-data').show();
// $('#getting-position').hide();
if(navigator.geolocation) {
$('#getting-position').html("navigator.geolocation");
navigator.geolocation.getCurrentPosition(showPosition, showError, { enableHighAccuracy: true });
} else {
alert('Geolocation API stöds inte i din webbläsare');
}
}
function showPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var accuracy = position.coords.accuracy;
var speed = position.coords.speed;
var altitude = position.coords.altitude;
var heading = position.coords.heading;
$('#getting-position').html(
"have position" +
" latitude = " + latitude.toString() +
" longitude = " + longitude.toString()
);
/* Add marker to Google maps etc... */
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
$('.map-fullsize').hide();
$('#weather-map').hide();
$('#weather-data').hide();
$('#permission-denied').show();
break;
case error.POSITION_UNAVAILABLE:
$('.map-fullsize').hide();
$('#weather-map').hide();
$('#weather-data').hide();
$('#position-unavailable').show();
break;
case error.TIMEOUT:
$('.map-fullsize').hide();
$('#weather-map').hide();
$('#weather-data').hide();
$('#timeout').show();
break;
case error.UNKNOWN_ERROR:
$('.map-fullsize').hide();
$('#weather-map').hide();
$('#weather-data').hide();
$('#unknown-error').show();
break;
}
}
$(document).ready(function() {
initialize();
});
</script>
</body>
</html>
Related
I'm trying to provide a direction service using WordPress.
And the API using here is APi but the map is only displaying blank and also when address is entered, it didn't return any result.
I bought a plugin from CodeCanyon but it's no longer supported.
This is the call I made:
wp_enqueue_style('jqmap-style-ui-slide', WP_PLUGIN_URL . '/JQMap_RouteCalc/css/jquery-ui-1.8.17.custom.css');
wp_register_script('jquery-JQMap_RouteCalcgoogleapis', 'https://maps.googleapis.com/maps/api/js?key=MY-KEY-HERE-kQ&libraries=places');
wp_enqueue_script('jquery-JQMap_RouteCalc',WP_PLUGIN_URL . '/JQMap_RouteCalc/js/jquery-JQMap_RouteCalc.js', array('jquery','jquery-ui-slider','jquery-JQMap_RouteCalcgoogleapis'));
And this is the JavaScript below
(function($){
//////////////////////// FUNCTION TO GIVE AUTOCOMPLETE TO EACH CALC INPUTS //////////////
function autocomplete_map(container){
container.find("input").each(function(){
new google.maps.places.Autocomplete($(this)[0]);
$(this).attr('placeholder','')
});
}
////////////////////////// FUNCTION TO PRIN ROUTE INFO ///////////
function print_route(panel){
var a = window.open('','','width=300,height=300');
a.document.open("text/html");
a.document.write(panel.html());
a.document.close();
a.print();
}
////////////////////////// START GOOGLE MAP API /////////////////
var myOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
, geocoder = new google.maps.Geocoder();
function center(imap,iaddress,info_window,zoom){
var map;
map = new google.maps.Map(imap, {
zoom: zoom,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var address = iaddress;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
if(info_window != ''){
var infowindow = new google.maps.InfoWindow({
content: info_window
});
infowindow.open(map,marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
setTimeout(function(){$('.map_container').find('img').css({'max-width':'none','max-height':'none'});},500);
}
function initialize(imap,ipanel,start,end,wp,travel_mode_select,opt_wp,printable_panel,DivContainerDistance) {
var directionsDisplay = new google.maps.DirectionsRenderer({draggable: true})
, directionsService = new google.maps.DirectionsService()
, oldDirections = []
, currentDirections;
map = new google.maps.Map(imap, myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(ipanel);
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
if (currentDirections) {
oldDirections.push(currentDirections);
}
currentDirections = directionsDisplay.getDirections();
computeTotalDistance(directionsDisplay.directions,DivContainerDistance);
});
var waypts = []
, dest = wp
, request = {
origin: start,
destination: end,
waypoints:waypts,
optimizeWaypoints:opt_wp,
travelMode: google.maps.DirectionsTravelMode[travel_mode_select]
};
for (var i = 0; i < dest.length; i++) {
if (dest[i].value != "") {
waypts.push({
location:dest[i].value,
stopover:true});
}
}
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
printable_panel.html('')
var route = response.routes[0];
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
printable_panel.append("<b>Route Segment: " + routeSegment + "</b><br />"
+route.legs[i].start_address + " to "+route.legs[i].end_address + "<br />"
+route.legs[i].distance.text + "<br /><br />");
}
}
if ( status != 'OK' ){ alert(status); return false;}
setTimeout(function(){$('.map_container').find('img').css({'max-width':'none','max-height':'none'});},500);
});
setTimeout(function(){$('.map_container').find('img').css({'max-width':'none','max-height':'none'});},500);
}
function computeTotalDistance(result,DivContainerDistance) {
var total = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000.
$(DivContainerDistance).html('Total Distance: '+total + " km")
}
////////////////////////// END GOOGLE MAP API /////////////////
I'm 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!
Can you please let me know if it is possible to get list of all places for example Gas Stations along Route Between Origin and Destination in Google Maps API? Here is a link that I am trying to list all Gas Stations or Rest areas ( or any of Google Maps API Supported Place Types)between two points ans based on a Direction supported route.
and this my code so far:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var haight = new google.maps.LatLng(49.216364,-122.811897);
var oceanBeach = new google.maps.LatLng(50.131446,-119.506838);
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: haight
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var request = {
origin: haight,
destination: oceanBeach,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Edited Part:
// Make the directions request
directionService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsRenderer.setDirections(result);
// Box around the overview path of the first route
var path = result.routes[0].overview_path;
var boxes = routeBoxer.box(path, distance);
drawBoxes(boxes);
} else {
alert("Directions query failed: " + status);
}
for (var i = 0; i < boxes.length; i++) {
var bounds = box[i];
// Perform search over this bounds
}
});
}
Use the RouteBoxer to get an array of google.maps.LatLngBounds objects that cover the route.
for each of those bounds use the Places library to search for the places.
Note that there are query limits and quotas on the places requests, so for long routes this may not be practical.
example
(however, looking at how the results are grouped, it looks like the places service is searching around the center of the bounds, rather than in the bounds, but it might be good enough for your needs).
code snippet:
var map = null;
var boxpolys = null;
var directions = null;
var routeBoxer = null;
var distance = null; // km
var service = null;
var gmarkers = [];
var boxes = null;
var infowindow = new google.maps.InfoWindow();
function initialize() {
// Default the map view to the continental U.S.
var mapOptions = {
center: new google.maps.LatLng(40, -80.5),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 8
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
service = new google.maps.places.PlacesService(map);
routeBoxer = new RouteBoxer();
directionService = new google.maps.DirectionsService();
directionsRenderer = new google.maps.DirectionsRenderer({
map: map
});
// If there are any parameters at eh end of the URL, they will be in location.search
// looking something like "?marker=3"
// skip the first character, we are not interested in the "?"
var query = location.search.substring(1);
// split the rest at each "&" character to give a list of "argname=value" pairs
var pairs = query.split("&");
for (var i = 0; i < pairs.length; i++) {
// break each pair at the first "=" to obtain the argname and value
var pos = pairs[i].indexOf("=");
var argname = pairs[i].substring(0, pos).toLowerCase();
var value = pairs[i].substring(pos + 1).toLowerCase();
// process each possible argname - use unescape() if theres any chance of spaces
if (argname == "to") {
document.getElementById('to').value = unescape(value);
}
if (argname == "from") {
document.getElementById('from').value = unescape(value);
}
if (argname == "dist") {
document.getElementById('distance').value = parseFloat(value);
}
if (argname == "type") {
document.getElementById('type').value = unescape(value);
}
if (argname == "keyword") {
document.getElementById('keyword').value = unescape(value);
}
if (argname == "name") {
document.getElementById('name').value = unescape(value);
}
if (argname == "submit") {
route();
}
}
}
function route() {
// Clear any previous route boxes from the map
clearBoxes();
// Convert the distance to box around the route from miles to km
distance = parseFloat(document.getElementById("distance").value) * 1.609344;
var request = {
origin: document.getElementById("from").value,
destination: document.getElementById("to").value,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
// Make the directions request
directionService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsRenderer.setDirections(result);
// Box around the overview path of the first route
var path = result.routes[0].overview_path;
boxes = routeBoxer.box(path, distance);
// alert(boxes.length);
drawBoxes();
findPlaces(0);
} else {
alert("Directions query failed: " + status);
}
});
}
// Draw the array of boxes as polylines on the map
function drawBoxes() {
boxpolys = new Array(boxes.length);
for (var i = 0; i < boxes.length; i++) {
boxpolys[i] = new google.maps.Rectangle({
bounds: boxes[i],
fillOpacity: 0,
strokeOpacity: 1.0,
strokeColor: '#000000',
strokeWeight: 1,
map: map
});
}
}
function findPlaces(searchIndex) {
var type = document.getElementById('type').value;
var keyword = document.getElementById('keyword').value;
var name = document.getElementById('name').value;
var request = {
bounds: boxes[searchIndex],
};
if (!!type && (type != "")) {
if (type.indexOf(',') > 0)
request.types = type.split(',');
else
request.types = [type];
}
if (!!keyword && (keyword != "")) request.keyword = keyword;
if (!!name && (name != "")) request.name = name;
service.nearbySearch(request, function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
document.getElementById('side_bar').innerHTML += "bounds[" + searchIndex + "] returns " + results.length + " results<br>"
for (var i = 0, result; result = results[i]; i++) {
var marker = createMarker(result);
}
} else {
document.getElementById('side_bar').innerHTML += "bounds[" + searchIndex + "] returns 0 results<br> status=" + status + "<br>";
}
if (status != google.maps.places.PlacesServiceStatus.OVER_QUERY_LIMIT) {
searchIndex++;
if (searchIndex < boxes.length)
findPlaces(searchIndex);
} else { // delay 1 second and try again
setTimeout("findPlaces(" + searchIndex + ")", 1000);
}
});
}
// Clear boxes currently on the map
function clearBoxes() {
if (boxpolys != null) {
for (var i = 0; i < boxpolys.length; i++) {
boxpolys[i].setMap(null);
}
}
boxpolys = null;
}
function createMarker(place) {
var placeLoc = place.geometry.location;
if (place.icon) {
var image = new google.maps.MarkerImage(
place.icon, new google.maps.Size(71, 71),
new google.maps.Point(0, 0), new google.maps.Point(17, 34),
new google.maps.Size(25, 25));
} else var image = {
url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
size: new google.maps.Size(7, 7),
anchor: new google.maps.Point(3.5, 3.5)
};
var marker = new google.maps.Marker({
map: map,
icon: image,
position: place.geometry.location
});
var request = {
reference: place.reference
};
google.maps.event.addListener(marker, 'click', function() {
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var contentStr = '<h5>' + place.name + '</h5><p>' + place.formatted_address;
if (!!place.formatted_phone_number) contentStr += '<br>' + place.formatted_phone_number;
if (!!place.website) contentStr += '<br><a target="_blank" href="' + place.website + '">' + place.website + '</a>';
contentStr += '<br>' + place.types + '</p>';
infowindow.setContent(contentStr);
infowindow.open(map, marker);
} else {
var contentStr = "<h5>No Result, status=" + status + "</h5>";
infowindow.setContent(contentStr);
infowindow.open(map, marker);
}
});
});
gmarkers.push(marker);
if (!place.name) place.name = "result " + gmarkers.length;
var side_bar_html = "<a href='javascript:google.maps.event.trigger(gmarkers[" + parseInt(gmarkers.length - 1) + "],\"click\");'>" + place.name + "</a><br>";
document.getElementById('side_bar').innerHTML += side_bar_html;
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
margin: 0;
padding: 0;
height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://cdn.jsdelivr.net/gh/denissellu/routeboxer#master/src/RouteBoxer.js" type="text/javascript"></script>
<table border="1">
<tr>
<td valign="top">
<div id="map" style="width: 600px; height: 500px;"></div>
</td>
<td>
<div id="side_bar" style="width:200px; height: 600px; overflow: auto"></div>
</td>
</tr>
</table>
Box within at least
<input type="text" id="distance" value="3" size="2">miles of the route from
<input type="text" id="from" value="denver" />to
<input type="text" id="to" value="oklahoma city, OK" />
<input type="submit" onclick="route()" />
<br>
<label>type</label>
<input type="text" id="type" value="gas_station" />
<label>keyword</label>
<input type="text" id="keyword" value="" />
<label>name</label>
<input type="text" id="name" value="" />
<div id="towns"></div>
Can you please let me know if it is possible to get list of all places for example Gas Stations along Route Between Origin and Destination in Google Maps API? Here is a link that I am trying to list all Gas Stations or Rest areas ( or any of Google Maps API Supported Place Types)between two points ans based on a Direction supported route.
and this my code so far:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var haight = new google.maps.LatLng(49.216364,-122.811897);
var oceanBeach = new google.maps.LatLng(50.131446,-119.506838);
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: haight
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var request = {
origin: haight,
destination: oceanBeach,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Edited Part:
// Make the directions request
directionService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsRenderer.setDirections(result);
// Box around the overview path of the first route
var path = result.routes[0].overview_path;
var boxes = routeBoxer.box(path, distance);
drawBoxes(boxes);
} else {
alert("Directions query failed: " + status);
}
for (var i = 0; i < boxes.length; i++) {
var bounds = box[i];
// Perform search over this bounds
}
});
}
Use the RouteBoxer to get an array of google.maps.LatLngBounds objects that cover the route.
for each of those bounds use the Places library to search for the places.
Note that there are query limits and quotas on the places requests, so for long routes this may not be practical.
example
(however, looking at how the results are grouped, it looks like the places service is searching around the center of the bounds, rather than in the bounds, but it might be good enough for your needs).
code snippet:
var map = null;
var boxpolys = null;
var directions = null;
var routeBoxer = null;
var distance = null; // km
var service = null;
var gmarkers = [];
var boxes = null;
var infowindow = new google.maps.InfoWindow();
function initialize() {
// Default the map view to the continental U.S.
var mapOptions = {
center: new google.maps.LatLng(40, -80.5),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 8
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
service = new google.maps.places.PlacesService(map);
routeBoxer = new RouteBoxer();
directionService = new google.maps.DirectionsService();
directionsRenderer = new google.maps.DirectionsRenderer({
map: map
});
// If there are any parameters at eh end of the URL, they will be in location.search
// looking something like "?marker=3"
// skip the first character, we are not interested in the "?"
var query = location.search.substring(1);
// split the rest at each "&" character to give a list of "argname=value" pairs
var pairs = query.split("&");
for (var i = 0; i < pairs.length; i++) {
// break each pair at the first "=" to obtain the argname and value
var pos = pairs[i].indexOf("=");
var argname = pairs[i].substring(0, pos).toLowerCase();
var value = pairs[i].substring(pos + 1).toLowerCase();
// process each possible argname - use unescape() if theres any chance of spaces
if (argname == "to") {
document.getElementById('to').value = unescape(value);
}
if (argname == "from") {
document.getElementById('from').value = unescape(value);
}
if (argname == "dist") {
document.getElementById('distance').value = parseFloat(value);
}
if (argname == "type") {
document.getElementById('type').value = unescape(value);
}
if (argname == "keyword") {
document.getElementById('keyword').value = unescape(value);
}
if (argname == "name") {
document.getElementById('name').value = unescape(value);
}
if (argname == "submit") {
route();
}
}
}
function route() {
// Clear any previous route boxes from the map
clearBoxes();
// Convert the distance to box around the route from miles to km
distance = parseFloat(document.getElementById("distance").value) * 1.609344;
var request = {
origin: document.getElementById("from").value,
destination: document.getElementById("to").value,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
// Make the directions request
directionService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsRenderer.setDirections(result);
// Box around the overview path of the first route
var path = result.routes[0].overview_path;
boxes = routeBoxer.box(path, distance);
// alert(boxes.length);
drawBoxes();
findPlaces(0);
} else {
alert("Directions query failed: " + status);
}
});
}
// Draw the array of boxes as polylines on the map
function drawBoxes() {
boxpolys = new Array(boxes.length);
for (var i = 0; i < boxes.length; i++) {
boxpolys[i] = new google.maps.Rectangle({
bounds: boxes[i],
fillOpacity: 0,
strokeOpacity: 1.0,
strokeColor: '#000000',
strokeWeight: 1,
map: map
});
}
}
function findPlaces(searchIndex) {
var type = document.getElementById('type').value;
var keyword = document.getElementById('keyword').value;
var name = document.getElementById('name').value;
var request = {
bounds: boxes[searchIndex],
};
if (!!type && (type != "")) {
if (type.indexOf(',') > 0)
request.types = type.split(',');
else
request.types = [type];
}
if (!!keyword && (keyword != "")) request.keyword = keyword;
if (!!name && (name != "")) request.name = name;
service.nearbySearch(request, function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
document.getElementById('side_bar').innerHTML += "bounds[" + searchIndex + "] returns " + results.length + " results<br>"
for (var i = 0, result; result = results[i]; i++) {
var marker = createMarker(result);
}
} else {
document.getElementById('side_bar').innerHTML += "bounds[" + searchIndex + "] returns 0 results<br> status=" + status + "<br>";
}
if (status != google.maps.places.PlacesServiceStatus.OVER_QUERY_LIMIT) {
searchIndex++;
if (searchIndex < boxes.length)
findPlaces(searchIndex);
} else { // delay 1 second and try again
setTimeout("findPlaces(" + searchIndex + ")", 1000);
}
});
}
// Clear boxes currently on the map
function clearBoxes() {
if (boxpolys != null) {
for (var i = 0; i < boxpolys.length; i++) {
boxpolys[i].setMap(null);
}
}
boxpolys = null;
}
function createMarker(place) {
var placeLoc = place.geometry.location;
if (place.icon) {
var image = new google.maps.MarkerImage(
place.icon, new google.maps.Size(71, 71),
new google.maps.Point(0, 0), new google.maps.Point(17, 34),
new google.maps.Size(25, 25));
} else var image = {
url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
size: new google.maps.Size(7, 7),
anchor: new google.maps.Point(3.5, 3.5)
};
var marker = new google.maps.Marker({
map: map,
icon: image,
position: place.geometry.location
});
var request = {
reference: place.reference
};
google.maps.event.addListener(marker, 'click', function() {
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var contentStr = '<h5>' + place.name + '</h5><p>' + place.formatted_address;
if (!!place.formatted_phone_number) contentStr += '<br>' + place.formatted_phone_number;
if (!!place.website) contentStr += '<br><a target="_blank" href="' + place.website + '">' + place.website + '</a>';
contentStr += '<br>' + place.types + '</p>';
infowindow.setContent(contentStr);
infowindow.open(map, marker);
} else {
var contentStr = "<h5>No Result, status=" + status + "</h5>";
infowindow.setContent(contentStr);
infowindow.open(map, marker);
}
});
});
gmarkers.push(marker);
if (!place.name) place.name = "result " + gmarkers.length;
var side_bar_html = "<a href='javascript:google.maps.event.trigger(gmarkers[" + parseInt(gmarkers.length - 1) + "],\"click\");'>" + place.name + "</a><br>";
document.getElementById('side_bar').innerHTML += side_bar_html;
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
margin: 0;
padding: 0;
height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://cdn.jsdelivr.net/gh/denissellu/routeboxer#master/src/RouteBoxer.js" type="text/javascript"></script>
<table border="1">
<tr>
<td valign="top">
<div id="map" style="width: 600px; height: 500px;"></div>
</td>
<td>
<div id="side_bar" style="width:200px; height: 600px; overflow: auto"></div>
</td>
</tr>
</table>
Box within at least
<input type="text" id="distance" value="3" size="2">miles of the route from
<input type="text" id="from" value="denver" />to
<input type="text" id="to" value="oklahoma city, OK" />
<input type="submit" onclick="route()" />
<br>
<label>type</label>
<input type="text" id="type" value="gas_station" />
<label>keyword</label>
<input type="text" id="keyword" value="" />
<label>name</label>
<input type="text" id="name" value="" />
<div id="towns"></div>
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>