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.
Related
I'm developing a JS webapp with Google Maps API.
I have to calculate the distance from A/D to B, B to C and C to A/D (please check the next image).
https://imgur.com/a/OiKJaXA
But, on the map, I have to render ONLY the second leg (legs[1], B to C). (check the image for more info)
https://imgur.com/a/zjQUu9h
What can I do to hide the first and last leg of my route? Of course, I could do another request, one for the map, one for the calculations, but I'm trying to be as efficient as possible.
My JS:
var mpos = "via Melzi deril 38 20154 Milano";
var madd = $("#i_madd_v").val() + ', ' + $("#i_madd_n").val() + ', ' + $("#i_madd_c").val();
var dadd = $("#i_dadd_v").val() + ', ' + $("#i_dadd_n").val() + ', ' + $("#i_dadd_c").val();
console.log(madd);
console.log(dadd);
function initMap() {
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer();
var centro = new google.maps.LatLng(45.462861, 9.186453);
var mapOptions = {
zoom:11,
center: centro,
disableDefaultUI: true
}
map = new google.maps.Map(document.getElementById('mappa'), mapOptions);
directionsRenderer.setMap(map);
calcRoute(directionsService, directionsRenderer);
}
function calcRoute(directionsService, directionsRenderer) {
var request = {
origin:mpos,
destination:mpos,
waypoints: [
{
location: madd,
stopover: true
},
{
location: dadd,
stopover: true
},
],
travelMode: 'DRIVING'
};
directionsService.route(request, function(response, status) {
if (status == 'OK') {
console.log(response);
console.log(status);
directionsRenderer.setDirections(response);
}
});
}
initMap();
});
If your route will always have 3 legs, and you always want to remove the 1st and last, you can modify the response from the directions service before passing it to the directions renderer:
directionsService.route(request, function(response, status) {
if (status == 'OK') {
response.routes[0].legs.splice(0,1); // remove 1st leg
response.routes[0].legs.splice(1,1); // remove last leg
directionsRenderer.setDirections(response);
} else alert("directions request failed:"+status);
});
proof of concept fiddle
code snippet:
var mpos = "via Melzi deril 38 20154 Milano";
var madd = "Monza, IT";
var dadd = "Segrate, IT";
function initMap() {
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer();
var centro = new google.maps.LatLng(45.462861, 9.186453);
var mapOptions = {
zoom: 11,
center: centro,
disableDefaultUI: true
}
map = new google.maps.Map(document.getElementById('mappa'), mapOptions);
directionsRenderer.setMap(map);
calcRoute(directionsService, directionsRenderer);
}
function calcRoute(directionsService, directionsRenderer) {
var request = {
origin: mpos,
destination: mpos,
waypoints: [{
location: madd,
stopover: true
},
{
location: dadd,
stopover: true
},
],
travelMode: 'DRIVING'
};
directionsService.route(request, function(response, status) {
if (status == 'OK') {
response.routes[0].legs.splice(0, 1);
response.routes[0].legs.splice(1, 1);
directionsRenderer.setDirections(response);
}
});
}
initMap();
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#mappa {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=&v=weekly"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="mappa"></div>
</body>
</html>
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
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);
i have try to calculate distance from 2 very far locations
and I expect that google give me a ZERO RESULT error becouse not find a right way from this 2 locations, but not give me this error And i can't intercept this error
just say me:
Uncaught TypeError: Cannot read property 'text' of undefined
Now my question is, how can i intercept this error ZERO RESULT?
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {
lat: -15.7942357,
lng: -47.8821945
}
});
var bounds = new google.maps.LatLngBounds;
var origin1 = {lat: -33.8688197, lng: 151.209295500000058};
var destinationB = {lat: 50.087, lng: 14.421};
var geocoder = new google.maps.Geocoder;
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: [origin1],
destinations: [destinationB],
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== 'OK') {
alert('Error was: ' + status);
} else {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('output');
var showGeocodedAddressOnMap = function(asDestination) {
return function(results, status) {
if (status === 'OK') {
map.fitBounds(bounds.extend(results[0].geometry.location));
} else {
alert('Geocode was not successful due to: ' + status);
}
};
};
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
geocoder.geocode({'address': originList[i]},
showGeocodedAddressOnMap(false));
for (var j = 0; j < results.length; j++) {
geocoder.geocode({'address': destinationList[j]},
showGeocodedAddressOnMap(true));
alert(results[j].distance.text);
alert(results[j].duration.text);
}
}
}
});
}
#map{
width:100%;
height:300px;
}
<html>
<head>
</head>
<body>
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSpQw&libraries=places&callback=initMap">
</script>
</body>
</html>
As I've mentioned about, the request is okay, hence why it returns the status, okay, you need to check each element for its status. View the code below especially the line results[j].status !== "OK"
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {
lat: -15.7942357,
lng: -47.8821945
}
});
var bounds = new google.maps.LatLngBounds;
var origin1 = {
lat: -33.8688197,
lng: 151.209295500000058
};
var destinationB = {
lat: 50.087,
lng: 14.421
};
var geocoder = new google.maps.Geocoder;
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: [origin1],
destinations: [destinationB],
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== 'OK') {
alert('Error was: ' + status);
} else {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('output');
var showGeocodedAddressOnMap = function(asDestination) {
return function(results, status) {
if (status === 'OK') {
map.fitBounds(bounds.extend(results[0].geometry.location));
} else {
alert('Geocode was not successful due to: ' + status);
}
};
};
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
geocoder.geocode({
'address': originList[i]
},
showGeocodedAddressOnMap(false));
for (var j = 0; j < results.length; j++) {
geocoder.geocode({
'address': destinationList[j]
},
showGeocodedAddressOnMap(true));
if (results[j].status !== "OK") {
alert("Not okay");
return;
}
alert(results[j].distance.text);
alert(results[j].duration.text);
}
}
}
});
}
#map {
width: 100%;
height: 300px;
}
<html>
<head>
</head>
<body>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCp5RzbQjgID4oHJYe6VRGhKGXpQTGtCmw&libraries=places&callback=initMap">
</script>
</body>
</html>
Before alert do a check something like below
// check if it has results
if(results[j].status === "OK") {
// do something with result
alert(results[j].distance.text);
alert(results[j].duration.text);
}
Google Maps API Status Code.
With the code below, I display a journey betwen two points.
Now I try to use direction result object and direction leg to get information like steps, legs or distance in a variable, but I have no idea to how use this method...
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var haight = new google.maps.LatLng(44.912198, -0.605530);
var oceanBeach = new google.maps.LatLng(44.893356, -0.739138);
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 14,
center: haight
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
calcRoute()
}
calcRoute()
function calcRoute() {
var request = {
origin: haight,
destination: oceanBeach,
// Note that Javascript allows us to access the constant
// using square brackets and a string value as its
// "property."
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);
Thanks
I've resolved a part of the problem with this code :
Variable duration, path, and polyline1 are ok, I've tried it with an alert.
Now I want to save those variables in a data base like sql, how I do ? using php ?
function calcRoute() {
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var warnings = document.getElementById('warnings_panel');
warnings.innerHTML = '<b>' + response.routes[0].warnings + '</b>';
directionsDisplay.setDirections(response);
showSteps(response);
}
});
}
function showSteps(directionResult) {
var myRoute = directionResult.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
var duration = myRoute.steps[i].duration.text;
var path = myRoute.steps[i].path;
var polyline1 = myRoute.steps[i].distance.text;
}
}