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. =/ =/ =/
Related
I am writing functions in my JavaScript file to output an address. It is not the cleanest, but it worked before my current issue came up. I am trying to callback and get an address but when I log the address to the console, it is undefined. I'm not sure what I am doing wrong.
function calculateDistance(vnames, vlocations) {
// PROGRAM NEVER GOES THROUGH THIS???
clientLoc((address) => {
var origin = address;
alert("Address: " + address);
});
// PROGRAM NEVER GOES THROUGH THIS???
console.log("my location is: " + origin);
var venueNames = vnames,
venueLocs = vlocations,
service = new google.maps.DistanceMatrixService();
// 5. Output band name and distance
// Matrix settings
service.getDistanceMatrix(
{
origins: [origin],
destinations: venueLocs,
travelMode: google.maps.TravelMode.DRIVING, // Calculating driving distance
unitSystem: google.maps.UnitSystem.IMPERIAL, // Calculate distance in mi, not km
avoidHighways: false,
avoidTolls: false
},
callback
);
// Place the values into the appropriate id tags
function callback(response, status) {
// console.log(response.rows[0].elements)
// dist2 = document.getElementById("distance-result-2"),
// dist3 = document.getElementById("distance-result-3");
for(var i = 1; i < response.rows[0].elements.length + 1; i++) {
var name = document.getElementById("venue-result-" + i.toString()),
dist = document.getElementById("distance-result-" + i.toString());
// In the case of a success, assign new values to each id
if(status=="OK") {
// dist1.value = response.rows[0].elements[0].distance.text;
name.innerHTML = venueNames[i-1];
dist.innerHTML = response.rows[0].elements[i-1].distance.text;
} else {
alert("Error: " + status);
}
}
}
}
This is the function I am using the callback from:
// Find the location of the client
function clientLoc (callback) {
// Initialize variables
var lat, lng, location
// Check for Geolocation support
if (navigator.geolocation) {
console.log('Geolocation is supported!');
// Use geolocation to find the current location of the client
navigator.geolocation.getCurrentPosition(function(position) {
console.log(position);
lat = position.coords.latitude;
lng = position.coords.longitude;
// Client location coordinates (latitude and then longitude)
location = position.coords.latitude + ', ' + position.coords.longitude
// console.log(location)
// Use Axios to find the address of the coordinates
axios.get('https://maps.googleapis.com/maps/api/geocode/json?key=AIzaSyAg3DjzKVlvSvdrpm1_SU0c4c4R017OIOg', {
params: {
address: location,
key: 'AIzaSyBH6yQDUxoNA3eV81mTYREQkxPIWeZ83_w'
}
})
.then(function(response) {
// Log full response
console.log(response);
var address = response.data.results[0].formatted_address;
// Return the address
console.log(address);
//return clientLoc.address;
// CALLBACK
callback(address);
})
});
}
else {
console.log('Geolocation is not supported for this Browser/OS version yet.');
return null;
}
}
a function that has a callback doesn't block execution, so your function clientLoc gets called and presumably if that code works, the origin variable will get set and your alert call will fire ... BUT the code below clientLoc is not waiting for the clientLoc call to finish ... it proceeds through the rest of the function ... granted i'm not too familiar with the es6 syntax but the concept is the same. You probably want to move the console.log("my location is: " + origin); and any code that reiles on the origin variable being set inside the callback, to make it cleaner use some promises
I'm doing my work with Google Map API. To draw a route between two points, I use this function:
function calcRoute(start, end) {
var pStart = new google.maps.LatLng(start.lat(), start.lng());
var pEnd = new google.maps.LatLng(end.lat(), end.lng());
var request = {
origin: pStart,
destination: pEnd,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
// Box the overview path of the first route
var path = result.routes[0].overview_path;
boxes = rboxer.box(path, distance);
//drawBoxes(boxes);
nearbyMarkets = search_market(boxes);
// PUT HERE???
}
});
}
After this, I need access the Direction Display object, which only available after the route is rendered successfully (means this function's done). I tried to put that code block in that position, but at that time, the Direction property of Direction Display is still not available, so it's failed. But if I call it after calcRoute function, it's OK.
So, my question is, how can I know when the callback finish so that I can continue my work? I've tried putting a flag like below, but it was unsuccessful, the loop is infinite.
function calcRoute(start, end) {
var pStart = new google.maps.LatLng(start.lat(), start.lng());
var pEnd = new google.maps.LatLng(end.lat(), end.lng());
var pass = false;
var request = {
origin: pStart,
destination: pEnd,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
// Box the overview path of the first route
var path = result.routes[0].overview_path;
boxes = rboxer.box(path, distance);
//drawBoxes(boxes);
nearbyMarkets = search_market(boxes);
pass = true;
}
});
while (!pass) {
}
}
Observe the directions_changed-event:
google.maps.event.addListener(directionsDisplay, 'directions_changed',function(){
if(this.get('directions')){
//directions are available, do something
}
});
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.
I made with Google Maps an route between two places. Thats works fine.
But i also have an database with interesting points on different roads in
my country. I like to show them if they are on the generated route. Places who are
not one this route, don't need to be shown.
My database with intereseting points contains latitude and longitude coordinates.
How can i check is they are on my route? There are approximately 30 or 40 interesting
point in my database.
// set request
var request = {
origin: initialLocation,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
};
// make route
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// set route
directionsDisplay.setDirections(response);
}
});
UPDATE:
Build new function "isLocationOnEdge". But the check runs the markers when they are not on the road:
// get flitsers on the route
function getFlitsersOnRoute(){
// set request
var request = {
origin: current_location,
destination: $('#gegevens').html(),
travelMode: google.maps.TravelMode.DRIVING
};
// make route
directionsService.route(request, function(response, status) {
// isLocationOnEdge
var isLocationOnEdge = google.maps.geometry.poly.isLocationOnEdge;
var coords = response.routes[0].overview_path;
var image = base_url+'external/afbeeldingen/google_markers/flitser.png';
// get flitsers
$.ajax({
type: "POST",
async:false,
url: base_url+"advies/get/9",
success: function (data) {
var result = jQuery.parseJSON(data);
// loop trough flitsers
$.each(result.flitsers.m, function(i, item) {
// latitude longitude
var latlng = item["#attributes"].gps.split(",");
// make google latlng
var myLatlng = new google.maps.LatLng(latlng[0],latlng[1]);
if (myLatlng,coords)
{
// set and define the marker
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
size: new google.maps.Size(15, 15),
icon: image,
title: 'Flitser'
});
}
});
}
});
});
}
isLocationOnEdge(point:LatLng, poly:Polygon|Polyline, tolerance?:number)
To determine whether a point falls on or near a polyline, or on or near the edge of a polygon, pass the point, the polyline/polygon, and optionally a tolerance value in degrees to google.maps.geometry.poly.isLocationOnEdge(). The function returns true if the distance between the point and the closest point on the line or edge falls within the specified tolerance. The default tolerance value is 10-9 degrees.
https://developers.google.com/maps/documentation/javascript/geometry
Include the geometry library in your Google Maps API request:
http://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry&sensor=TRUE_OR_FALSE
Pseudo-code:
// Make isLocationOnEdge easier to access
var isLocationOnEdge = google.maps.geometry.poly.isLocationOnEdge;
for (var i = 0; i < interestingPlaces.length; i++) {
if (isLocationOnEdge(interestingPlaces[i],
response.routes[0].overview_path))
{
// Do something with interestingPlaces[i]
}
}
Google maps documentation for isLocationOnEdge()
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
};