Taking the value of a variable for unitSystem in maps - javascript

I have a variable: units. This contains either metric or imperial.
Ok, so in Google maps directions the following is happening:
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.WALKING,
unitSystem: UnitSystem.METRIC
};
My noobish question is: How do i change "unitSystem: UnitSystem.METRIC" into "unitSystem: units". I simply don't know what Google is expecting for as a value. Cant find it in docs either.

As statued in https://developers.google.com/maps/documentation/javascript/distancematrix?hl=fr
unitSystem (optional) — The unit system to use when displaying
distance. Accepted values are:
google.maps.UnitSystem.METRIC (default)
google.maps.UnitSystem.IMPERIAL
So I guess you could do :
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.WALKING,
unitSystem: unit == 'metric' ? google.maps.UnitSystem.METRIC : google.maps.UnitSystem.IMPERIAL
};

Related

How to I get distance "value" from google maps distance matrix api?

I am autofilling an input field with the below which gives me distance.text value which is expressed in km but I'd like to get the distance.value for precision distance.
function getdistance(address){
var dest_address = address; // Address enter by user
var origin_address = document.getElementById('hall').value ; // Address where you need to calculate distance.
var distanceService = new google.maps.DistanceMatrixService(); // store Google Distance Service method
// Call distance matrix services.
// default parameters
distanceService.getDistanceMatrix({
origins: [dest_address],
destinations: [origin_address],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
durationInTraffic: true,
avoidHighways: false,
avoidTolls: false
},
function (response, status) {
// check status from google service call
if (status !== google.maps.DistanceMatrixStatus.OK) {
console.log('Error:', status);
} else {
// Response contain JSON.
var error = response.rows[0].elements[0].status;
$('#error').html(error);
var distance = response.rows[0].elements[0].distance.value;
document.getElementById("distance").value = distance;
}
});
}
I tried changing
var distance = response.rows[0].elements[0].distance.text;
to
var distance = response.rows[0].elements[0].distance.value;
but still only getting the "text" value.
Please help
Actually, Sorry! changing the line to...
var distance = response.rows[0].elements[0].distance.value;
...works. I just needed to clear my cache for the .js file change to kick in. =/ =/ =/

Google Maps API asynchronous

I'm currently working with the Google Maps API. I use the globalFunction when user click on some button. The "calcRoad" function generate the road by using the Google Maps API, and then "Myfunction" use the data from "calcRoad" to do some calculation.
My problem is that right now "Myfunction" doesn't wait "calcRoad" to end before starting. I asume that some of the Google API requests are asynchronous but I can't access the code behind it.
How could I forced "Myfunction" to wait until "calcRoad" is done ?
function globalFunction(){
calcRoad(true,latitude, longitude);
Myfunction();
}
function calcRoad(bool,lat,long) {
marker.setVisible(false);
var date = new Date();
// Add a waypoint
if(bool){
var tampon = new google.maps.LatLng(lat,long);
waypoints.push({
location: tampon,
stopover:false
});
}
var request = {
origin: departure_place.geometry.location,
destination: arrival_place.geometry.location,
travelMode: google.maps.TravelMode[mode],
waypoints: waypoints,
avoidHighways: false,
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
PS: I tried to use some setTimeout before calling "Myfunction" and it is working but as I don't know how long will the "calcRoad" take to finish (depending on users' parametres) I can't use setTimeout.
I hope that I'm clear with my probleme, thanks in advance for your help.
You should add a callback parameter in your calcRoad function :
function globalFunction(){
calcRoad(true,latitude, longitude, Myfunction);
}
function calcRoad(bool,lat,long, cb) {
marker.setVisible(false);
var date = new Date();
// Add a waypoint
if(bool){
var tampon = new google.maps.LatLng(lat,long);
waypoints.push({
location: tampon,
stopover:false
});
}
var request = {
origin: departure_place.geometry.location,
destination: arrival_place.geometry.location,
travelMode: google.maps.TravelMode[mode],
waypoints: waypoints,
avoidHighways: false,
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
cb && cb(); // Check if "cb" callback function is defined and execute it
}
});
}
Something like this should work !

Google Direction Service - Route from current location to defined destination [duplicate]

This question already has an answer here:
Get directions to predefined destination from current location (Geolocation)
(1 answer)
Closed 5 years ago.
This is my script which currently displays a route for either car or transit depending on what the user has selected.
Would anyone know how to adapt this script to set the origin as the users current location and route from that to set lat + long destination.
As I have currently been unable to find a way to integrate this within my script - any help would be much appreciated!
function initMap() {
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: {lat: *VALUE*, lng: *VALUE*}
});
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('right-panel'));
calculateAndDisplayRoute(directionsService, directionsDisplay);
document.getElementById('mode').addEventListener('change', function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
});
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var selectedMode = document.getElementById('mode').value;
directionsService.route({
origin: {lat: *VALUE*, lng: *VALUE*}, // Haight.
destination: {lat: *VALUE*,lng: *VALUE*}, // Ocean Beach.
// Note that Javascript allows us to access the constant
// using square brackets and a string value as its
// "property."
travelMode: google.maps.TravelMode[selectedMode],
transitOptions: {
arrivalTime: new Date(1489242600000),
routingPreference: 'FEWER_TRANSFERS'
},
unitSystem: google.maps.UnitSystem.IMPERIAL,
provideRouteAlternatives: true
}, function(response, status) {
if (status == 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
In the google directions API you can read what parameters you can add. In your case you would need origin and destination and maybe waypoints if you are planning to make a route with multiple stops.
https://developers.google.com/maps/documentation/directions/intro#Waypoints
In the link below there is an example how you can select multiple way points. For the location you can use Geolocation to get the latitude and longitude. Those can be implemented in the calculateAndDisplay function in the origin parameter.
directionsService.route({
origin: //here you can put lat/long or a name
destination: //here you can put lat/long or a name
waypoints: // waypoints expect an Array of locations or lat/long
optimizeWaypoints: true,
travelMode: 'DRIVING'
},
https://developers.google.com/maps/documentation/javascript/examples/directions-waypoints

Google Maps API: ZERO RESULTS or INVALID REQUEST while drawing routes

I am trying to draw a route based on the co-ordinates that i receive from the database. But somehow i am not able to draw. I either get ZERO RESULTS or INVALID REQUEST.. The route i am trying to draw is a TRANSIT ROUTE. Where as i found some similar issues(Link) being addressed in the site but the solution given was to add departure time or arrival time in the parameters. And it was an accepted answer. The same which i tried is not working currently. I have posted the code that i have tried.
Below are the co-ordinates:
19.1860640243063 72.9759523272514
19.1902699 73.023094
19.2178474133021 73.086293040406
19.2354157727173 73.1302742969937
Please help.
load : function(response)
{
for(var i=0;i<response.length;i++)
{
if(response[i].linkData!='undefined')
{
link=response[i].linkData;
var lastPos=(response.length-1);
linkDes=response[lastPos].linkData;
var linkDes=link.split(" ");
var linkValue=link.split(" ");
var latDes= parseFloat(linkDes[0]);
var longDes= parseFloat(linkDes[1]);
var lat = parseFloat(linkValue[0]); //convert string to float
var lon = parseFloat(linkValue[1]); //convert string to float
if(count==0)
{
var source=new google.maps.LatLng(lat, lon);
count++;
}
if(i!=0 )
{
geoLatLong=new google.maps.LatLng(lat, lon);
count++;
}
if(i!=response.length-1)
{
geoLatLong=new google.maps.LatLng(lat, lon);
}
if(latDes!="" && longDes!="")
{
var destination=new google.maps.LatLng(latDes, longDes);
}
if(count>1 && count<=response.length-1)
{
geoLatLongArray.push(geoLatLong);
}
}
}
for(var i=0;i<geoLatLongArray.length;i++)
{
waypts.push({location:geoLatLongArray[i],stopover:true});
}
var request = {
origin: source,
destination: destination,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.TRANSIT,
transitOptions:
{
departureTime: new Date()
}
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
alert("directions response "+status);
}
});
}
According to v3 API Docs
google.maps.TravelMode.TRANSIT
is the correct syntax.
I had similar issue. I fixed it after making origin to an address field (instead of coordinates). this issue persists only when both origin and destination are coordinates.
You can perhaps convert your coordinates into address using Reverse Geocode API and then pass the converted addresses to origin / destination.

Google maps drawing path works till some point

I have an array with latlang values, and i want to draw a path which follows this values. This is what i did but it only draws till some point. When i console.log the 'result', expect the drawn objects, it prints
Uncaught Error: Error in property <routes>: (Cannot read property 'routes' of null)
function renderDirections(result) {
var directionDisplay = new google.maps.DirectionsRenderer();
directionDisplay.setMap(map);
directionDisplay.setDirections(result);
directionDisplay.setOptions({suppressMarkers: true});
}
for(var i=0; i < array.length; i++){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(array[i].lat, array[i].lng),
map: map
});
var directionsService = new google.maps.DirectionsService();
directionsService.route({
origin: new google.maps.LatLng(array[i].lat, array[i].lng),
destination: new google.maps.LatLng(array[i+1].lat, array[i+1].lng),
unitSystem: google.maps.UnitSystem.IMPERIAL,
travelMode: google.maps.DirectionsTravelMode.DRIVING
},
function(result){
renderDirections(result);
});
}
Check the "status" of the DirectionsService. The DirectionsService is subject to a quota and rate limits.
directionsService.route({
origin: new google.maps.LatLng(array[i].lat, array[i].lng),
destination: new google.maps.LatLng(array[i+1].lat, array[i+1].lng),
unitSystem: google.maps.UnitSystem.IMPERIAL,
travelMode: google.maps.DirectionsTravelMode.DRIVING
},
function(result, status){
if (status == google.maps.DirectionsStatus.OK)
renderDirections(result);
else alert ("Directions request failed:"+status);
});
The problem with "Uncaught TypeError: Cannot read property 'lat' of undefined" is due to your logic. array[i+1] does not exist when you get to your last directions request. Try this:
for(var i=0; i < array.length-1; i++){
example using function closure
This example of stringing multiple requests together may help you as well.

Categories