Drawing googlemap route on map with below coordinates.But getting wrong route. Where is the issue?
LNG LAT
58.5589893333333 23.6229513333333 Start
58.5589985 23.6231225 WAY POINT 1
58.5591366666667 23.6235491666667 WAY POINT 2
58.55882 23.6236481666667 WAY POINT 3
58.5476361666667 23.6209141666667 WAY POINT 4
58.5454098333333 23.616038 END
the wrong route
Same coordinates tried in Google map website,It is giving correct way
Where is the problem? Sending all the waypoints, origin and destination correctly. The coordinates are from tracking devices. only some cases showing wrong route like this.
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
var first = new google.maps.LatLng(23.6231225,58.5589985);
var second = new google.maps.LatLng(23.6235491666667,58.5591366666667);
var third = new google.maps.LatLng(23.6236481666667,58.55882);
var forth = new google.maps.LatLng(23.6209141666667,58.5476361666667);
var i = 0;
var start = StartlatDir[i]+','+StartlongDir[i];
var end = EndlatDir[i] + ',' + EndlongDir[i];
var request = {
origin: start,
destination: end,
waypoints: [{ location:first, stopover: false },
{ location: second, stopover: false },
{ location: third, stopover: false },
{ location: forth, stopover: false }],
optimizeWaypoints: false,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var myRoute = response.routes[0];
var txtDir = '';
for (var i = 0; i < myRoute.legs[0].steps.length; i++) {
txtDir += myRoute.legs[0].steps[i].instructions + "<br />";
}
}
});
The DirectionsService is very sensitive to waypoints near exits (or on the wrong side of the road).
Waypoint 4 (23.6209141666667, 58.5476361666667) makes the route take the exit.
Moving it further along the road to (23.620315,58.5471) gives the expected route:
fiddle
or removing it completely gives the expected route
fiddle
Related
Hi is it possible to get the direction from googlemaps without showing a map?
I can get the directions from calling like this:-
https://maps.googleapis.com/maps/api/directions/json?origin=52.4076963,-1.4853391999999985&destination=52.6114729,-1.6812878000000637&key=KEYHERE
<div id="result"></div>
And the code I am trying to call it with is :
function calcRoute() {
var start = "52.4076963,-1.4853391999999985";
var end = "52.6114729,-1.6812878000000637";
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var result = document.getElementById('result');
result.innerHTML= "";
for (var i =0; i < response.routes[0].legs[0].steps.length; i++){
result.innerHTML+=response.routes[0].legs[0].steps[i].instructions+"<br>"
}
console.log(response)
directionsDisplay.setDirections(response);
}
});
}
calcRoute();
How I get this to run with calcRoute and just show the direction in the div?
Thanks
To display the directions text without a map using the Google Maps Javascript API v3:
don't set the map property of the DirectionsRenderer
set the panel property of the DirectionsRenderer
function calcRoute() {
var directionsService = new google.maps.DirectionsService();
var start = "52.4076963,-1.4853391999999985";
var end = "52.6114729,-1.6812878000000637";
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setPanel(document.getElementById('result'));
directionsDisplay.setDirections(response);
}
});
}
proof of concept fiddle
function initialize() {
function calcRoute() {
var directionsService = new google.maps.DirectionsService();
var start = "52.4076963,-1.4853391999999985";
var end = "52.6114729,-1.6812878000000637";
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setPanel(document.getElementById('result'));
directionsDisplay.setDirections(response);
}
});
}
calcRoute();
}
google.maps.event.addDomListener(window, "load", initialize);
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="result"></div>
The solution to a lot of "how to use the maps API without showing a map?" questions assumes that it's going to be ok to use setPanel and for a journey plan to appear on your page instead of a map.
In case anyone wondered, if you don't want this and just want to extract data from the API without any google html being injected into your page at all you still need to use setPanel, but parse a null to it.
directionsDisplay.setPanel(null);
We Need Draw Direction between some points in Google maps.We tried but DirectionsStatus comes "zero results".We tried like this
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = {
zoom: 6,
center: chicago
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
debugger;
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < myjson.length; i++) {
var data = myjson[i];
waypts.push({
location: new google.maps.LatLng(parseFloat(myjson[i].Lattitude), parseFloat(myjson[i].Longitude)),
stopover: true
});
}
debugger;
console.log(waypts);
var request = {
origin:waypts[0].location,
destination:waypts[waypts.length-1].location,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
debugger;
directionsService.route(request, function(response, status) {
debugger;
if (status == google.maps.DirectionsStatus.OK) {
debugger;
directionsDisplay.setDirections(response);
var route = response.routes[0];
}
});
}
We need Status code "OK".Please help me.tell me What wrong in my code.WE have json and then JSON data pass to Myjson variable.calcRoute method call in button action.
When we print waypoints
Array[6]0: Objectlocation: kfD: 78.54940429999999k: 17.4211137__proto__: kfstopover: true__proto__: Object1: Objectlocation: kfstopover: true__proto__: Object2: Objectlocation: kfstopover: true__proto__: Object3: Object4: Object5: Objectlength: 6
From the output, it seems like there are something wrong with your myjson (array?).
Anyway, when I try to reproduce it, it works.
//from how you use your myjson var, I would assume it looks something like this:
var myjson = [
{ Lattitude: 37.4184, Longitude: -122.0880 },
{ Lattitude: 37.7833, Longitude: -122.4167 },
{ Lattitude: 38.5539, Longitude: -121.7381 }
]
var waypts = [];
for (var i = 0; i < myjson.length; i++) {
var data = myjson[i];
waypts.push({
location: new google.maps.LatLng(parseFloat(myjson[i].Lattitude), parseFloat(myjson[i].Longitude)),
stopover: true
});
}
console.log(JSON.stringify(waypts));
var request = {
origin:waypts[0].location,
destination:waypts[waypts.length-1].location,
waypoints: waypts.slice(1, waypts.length-1),
//the example in the documentation does not include the start & end points
//that might be a problem https://developers.google.com/maps/documentation/javascript/directions#DirectionsRequests
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
When printing waypoints
[{"location":{"k":37.4184,"D":-122.08799999999997},"stopover":true},{"location":{"k":37.7833,"D":-122.41669999999999},"stopover":true},{"location":{"k":38.5539,"D":-121.73810000000003},"stopover":true}]
Hope this help
In my case, the data came from an HTML li element, but it came as a String, i.e.
coordsData = {
lat: {
value: "19.4921383",
someOtherProperties: {}
},
lng: {
value: "-99.04651999999999",
someOtherProperties: {}
}
}
So, I had to convert those values like:
var myCoords = new google.maps.LatLng(parseFloat(coordsData.lat.value), parseFloat(coordsData.lng.value))
Just in case someone comes across the same issue.
I'm using Google API V3, and JavaScript and want to calculate the delay to get from one point to another that is caused by the traffic.
So, I made two requests (also see code below): One with durationInTraffic = true and one with durationInTraffic = false Strangely enough, both return the same values (I tested several bigger areas like Munich, Berlin, London, Sidney). Now I wonder whether my code is wrong or there are simply no traffic data available in the requested area.
function getRoute(){
var directionsService = new google.maps.DirectionsService();
var myOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var startValue=document.getElementById('start').value;
var zielValue=document.getElementById('ziel').value;
var stundeValue=document.getElementById('stunde').value;
var minuteValue=document.getElementById('minute').value;
var tagValue=document.getElementById('tag').value;
var monatValue=document.getElementById('monat').value;
var jahrValue=document.getElementById('jahr').value;
//departure time in Epoch time
var abfahrtsZeitValue=monatValue+"/"+tagValue+"/"+jahrValue+" "+stundeValue+":"+minuteValue;
var request_withTraffic = {
origin: startValue,
destination: zielValue,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
transitOptions: {
departureTime: new Date(abfahrtsZeitValue)
},
durationInTraffic: true
};
var request_withoutTraffic = {
origin: startValue,
destination: zielValue,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
transitOptions: {
departureTime: new Date(abfahrtsZeitValue)
},
durationInTraffic: false
};
directionsService.route(request_withTraffic, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// Display the duration:
document.getElementById('durationWithTraffic').innerHTML="Dauer mit Vekehr: ";
document.getElementById('durationWithTraffic').innerHTML +=
response.routes[0].legs[0].duration.value + " seconds";
}
});
directionsService.route(request_withoutTraffic, function(response, status) {
if (status == google.maps.DirectionsStatus.OK)
{
document.getElementById('durationWithoutTraffic').innerHTML="Dauer ohne Verkehr: ";
document.getElementById('durationWithoutTraffic').innerHTML +=
response.routes[0].legs[0].duration.value + " seconds";
}
});
}
I'm currently making an app for a university assignment. I'm using the google maps places api and gmaps.js.
What I want to do is let user search places and show the results in a simple list (which I've got working) but I want to calculate the distance to each of the search results as well, which is sort of working (I think!) but I'm not sure how to make it display how I want, e.g:
"Search Result - 1.1 mi away"
"Search Result - 0.8 mi away"
What it is doing right now is calculating the distances but all the values are being set next to all of the search results, instead of next to each other. In one line (all bunched together).
(Had to remove a link to post a new one)
I don't know how to split them or do it more cleanly from the start. I think the problem lies in the function which is calculating the distances using "google.maps.DistanceMatrixService".
var origin = currentLocation;
var destination = place.geometry.location;
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.WALKING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, getDistance);
function getDistance(response, status) {
if (status == "OK") {
var distance = response.rows[0].elements[0].distance.text;
console.log(distance);
$(".distance").append(distance);
} else {
return false;
console.log(response + status)
}
}
getDistance();
This line is my best guess:
response.rows[0].elements[0].distance.text;
But I'm quite lost with it.
Full code of my search request:
$("#place-search").submit(function(e){
e.stopPropagation(); e.preventDefault();
var query = $("#place-query").val();
map.addLayer("places", {
location: cheltenham, //new google.maps.LatLng(51.902707,-2.073361),
radius: 500, //experiment with the distance (in metres)
query: query,
opennow: true,
textSearch: function (results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
$(".results-list").html(""); //remove previous results
removeMarkers(); //remove previous markers
var bounds = new google.maps.LatLngBounds();
//console.log(bounds);
//I think if we set i to say 10, it will limit the search results - by default the places api returns 20 result sets
for (var i = 0; i < results.length; i++) {
//console.log(i);
var place = results[i];
var image = { //set to better sizes and positions (icons from search results)
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
/* ---------- */
var origin = currentLocation; //new google.maps.LatLng(51.902707,-2.073361);
var destination = place.geometry.location; //new google.maps.LatLng(51.899464, -2.074641);
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.WALKING, //this needs to be a choice
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, getDistance);
function getDistance(response, status) {
if (status == "OK") {
var distance = response.rows[0].elements[0].distance.text; //the one I need
console.log(distance);
$(".distance").append(distance);
} else {
return false;
console.log(response + status)
}
}
getDistance();
/* ---------- */
map.addMarker({
lat: place.geometry.location.lat(),
lng: place.geometry.location.lng(),
icon: image,
animation: google.maps.Animation.DROP,
title: place.name,
//we need to style and build these better - ideas? should be simple I think, Name + Location + Image
infoWindow: {
content: '<h2>'+place.name+'</h2>' + '<p>Rating: '+place.rating+'</p>' + '<p>'+(place.vicinity ? place.vicinity : place.formatted_address)+'</p><img src="'+place.icon+'"" width="100"/>'
}
});
bounds.extend(place.geometry.location);
$(".results-list").append("<li>" + place.name + "<span class=\"distance\"></span></li>");
}
map.fitBounds(bounds); //fit to the new bounds
}//end if search OK
}
});
});
Any help or pointers would be greatly appreciated!
Update:
I've tried moving the line that puts the items into the list with jQuery into the function getDistance(), and that ends up putting the distances with the place name but it's the same place name for every distance that is calculated. It is the last result from the search.
getDistance()
function getDistance(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];
$(".results-list").append("<li><span class=\"name\">" + place.name + "</span>" + distance + "</li>")
}
}
} else {
return false;
console.log(response + status)
}
}
What the output looks like: http://i.imgur.com/FSCMMzF.png
Thanks to everyone who's taken a look so far!
Basically I want to turn off the feature that centers the map on each turn when you click on Directions Panel step.
Is there a way to disable that feature?
PS: i tried:
suppressMarkers: true,
suppressInfoWindows: true,
but those only take out the markers and infowindows - it still centers the map on the turn point when its clicked.
You can render the DirectionsPanel yourself (rather than using the DirectionsRenderer). That gives you complete control.
Example
So this is what I ended up doing:
function getDirections()
{
var request =
{
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
var summaryPanel = document.getElementById('directions_steps');
directionsService.route(request, function(response, status)
{
if (status == google.maps.DirectionsStatus.OK)
{
directionsDisplay.setMap(map);
directionsDisplay.setDirections(response);
var legs = response.routes[0].legs;
for (var leg = 0; leg < legs.length; leg++) {
for (var step = 0; step < legs[leg].steps.length;
step++) {
if (legs[leg].steps[step].lat_lngs) {
summaryPanel.innerHTML += legs[leg].steps[step].instructions+"<br/><br/>";
}
}
}
}
});
}
Completely late, but for future references what worked for me was commenting these lines:
var directionsRenderer = new google.maps.DirectionsRenderer({
draggable: true,
map: map//,
//panel: document.getElementById('right-panel') step directions instructions here
});