Live traffic duration time is different from Google Map application and Google Map Distance Matrix API response.
I have tried the following way to get live traffic duration as showing the Google Map application.
First Way
https://maps.googleapis.com/maps/api/distancematrix/json?
key=<MyKey>&origins=-33.6771817,151.12005739999995&
destinations=-33.7704818,150.98828609999998&travelMode=DRIVING&
departure_time=[Current UTC Time]
Second Way
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [{lat: <lng>, lng: <lng>}, 'Origin Name'],
destinations: ['Destination Name', {lat: <lat>, lng: <lng>}],
travelMode: 'DRIVING',
drivingOptions: {
departureTime: [CurrentUTCTime>],
trafficModel: 'best_guess'
}
}
API results are successfully received but "duration_in_traffic" node value is not match with Google Map Application's live traffic duration time (please refer the attached images)
please assist me what am i doing wrong in this. thanks in advance.
I can get the exact "draffic_in_duration" value by using the first way with departure_time parameter value as now
https://maps.googleapis.com/maps/api/distancematrix/json?
key=<MyKey>&origins=-33.6771817,151.12005739999995&
destinations=-33.7704818,150.98828609999998&travelMode=DRIVING&
departure_time=now
cheers
Related
I am trying to draw a route between point A to point B. I have been following the link below:
https://developers.google.com/maps/documentation/directions/intro
Following link is an example of how to get the route between Montreal and Toronto.
https://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&key=API_KEY
I get a JSON Response when I run this URL. I have checked a lot, but not able to figure how to render the details from this response into a map. Can someone please help by pointing me in the right direction ?
I have already checked this link:
https://developers.google.com/maps/documentation/javascript/examples/directions-simple
I am using alexpechkarev/google-maps package, and Laravel for building this solution. I have run the directions service from the package, which returns the JSON object which is similar to the one given by the link in the google maps api guide.
Any help is appreciated.
Thanks.
Here is the general recipe:
You need to extract the coordinates of the route from the JSON response.
These are in the response at 2 levels of detail.
The explicit coordinates of the major intersections along the route. You can read these in plain English and you can extract them as associative array members.
In addition to above, there is a coded string containing lots more (lat, lon) pairs of the points between the intersections. You have to decode these and there is an algorithm available. (I did a PHP version a few weeks ago and link is below). BTW the reason for this second array is this: Imagine a long winding country road with no intersections... this array will follow the road curves, giving (lat,lon) pairs not found in 1.
3). Build an array of coordinates (from 1 and including 2 if you need finer detail).
4) Then use code like below (stolen from below link and adjusted a bit: https://developers.google.com/maps/documentation/javascript/examples/polyline-simple:) that shows you how to draw the lines on a map.
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: 0, lng: -180},
mapTypeId: 'terrain'
});
var routeCoordinates = [ // put your array here
{lat: 37.772, lng: -122.214},
{lat: 21.291, lng: -157.821},
{lat: -18.142, lng: 178.431},
{lat: -27.467, lng: 153.027}
];
var routePath = new google.maps.Polyline({
path: routesCoordinates,
geodesic: true,
strokeColor: '#FF0000', // adjust line colour
strokeOpacity: 1.0, // adjust line opacity
strokeWeight: 2 // adjust line thickness
});
routePath.setMap(map);
}
</script>
The example at the google link shows you how to do the tiny bit a HTML involved etc.
Now for the good bit to decode the polyline points:
Get itinerary latitudes & longitude from google maps with PHP
In above the function decodePolylinePoints($pointsString) returns an array of (lat,lons) that you can use for drawing the route.
You need to study the JSON to understand the code, and while it looks messy its perfectly logical. Put the JSON in an editor like VSCode and it will be displayed properly formatted.
I am using the static image API (where you pass a URL to Google and it returns an image). My issue is the images google is returning are sometimes not straight-on/clear view of the address. I am looking to get the same image as what the Google Maps search feature comes up with as a thumbnail.
I have read the Google Documentation for this API. An example URL is: https://maps.googleapis.com/maps/api/streetview?parameters&size=640x640&fov=50&location=4113+Hartford+Dr+Garland+TX
If I put this same address (4113 Hartford Dr, Garland, TX) directly into Google Maps, I get a much cleaner image.
I have experimented with changing the FOV value. My only other idea is to use heading, but I am unsure about this.
The end implementation is in Excel using VBA.
Let me know if you need any additional information.
You are going to have to compute the heading. I don't have the raw math for that, but here is an example using the JS API, if that's an option.
function getStreetView(lat, lng) {
let panorama = new google.maps.StreetViewPanorama(
document.getElementById('panorama'), {
position: {lat: lat, lng: lng}
})
let service = new google.maps.StreetViewService
service.getPanoramaByLocation(panorama.getPosition(), 50, function(panoData) {
if (panoData) {
let panoCenter = panoData.location.latLng
let heading = google.maps.geometry.spherical.computeHeading(panoCenter, {lat: lat, lng: lng})
let pov = panorama.getPov()
pov.heading = heading
panorama.setPov(pov)
} else {
alert('no streetview found')
}
})
map.setStreetView(panorama) // set dude on map
}
I have a SPA that I need to be able to provide the user directions between two points. I want the directions to work that same way that they do currently on the web version of google maps. IE. https://www.google.ca/maps/dir/ in the hosted by google web version when you request directions it will give you the fastest route considering traffic... (See Screenshot)
Currently when I issue the request using the following code it only returns a single route that does not consider traffic.
var directionsService = this.get('directionsService');
var directionsDisplay = this.get('directionsDisplay');
directionsService.route({
origin: new google.maps.LatLng(this.get('currentLocation.lat'),this.get('currentLocation.lng')),
destination: new google.maps.LatLng(toAddress.lat,toAddress.lng),
travelMode: 'DRIVING',
provideRouteAlternatives: true
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
Does anyone know thr correct way to do this?
Check number of routes returned by DirectionService.route, the callback will have a DirectionsResult object with an array of DirectionsRoute, which contains the information about the legs and steps its composed.
If its only returning 1 route, try to set provideRouteAlternatives to true in your DirectionsRequest object.
Happy coding!
TyBourque.
I think current google map API doesn't support direction map with traffic layer.
It is only available using embedded map API.
If you have already found the best solution (not using embedded map API), please write here
Regards
I am currently working with the Google Maps API to render directions.
From the technical side everything works fine:
var $canvas = $element.querySelector('#map-canvas');
vvar map = new maps.Map($canvas, {
center: new maps.LatLng(52.46004869999999, 13.37898690),
mapTypeId: maps.MapTypeId.ROADMAP,
zoom: 14
});
var route = {
travelMode: google.maps.TravelMode.BICYCLING,
origin: new google.maps.LatLng(52.455833, 13.322948),
destination: new google.maps.LatLng(52.459281, 13.356367),
};
new google.maps.DirectionsService().route(route, function(body) {
var display = new google.maps.DirectionsRenderer();
display.setMap(map);
display.setDirections(body);
});
Unfortunately the suggested route is absolutely crap. Instead of going directly from A to B it even leaves the city...
Why does this work good with maps.google.com but not with the API? What do I have to change so I get a correct result?
Bodo
The origin is placed on a train station, it seems the DirectionsService suggests to put the car on a train, because there is a vehicle Shipping available.
Google-Maps doesn't use the exact origin, it seems that it geocodes the LatLng and takes the result with type "street_address"(it's Berlinickestraße 16A, 12165 Berlin, Deutschland) as origin.
You may do the same(geocode the LatLng's first and use the results with a type of street_address as origin and destination)
Update:
I have some gps locatiwaon points and i want to draw the path.I the way draw using polylines which dont follow road.I want to do "snap to road",so that i can improve the way path.
I referred this code to snap to road for the locations saved in array "snap_path_points"
I am getting path only for first 8 calls (limitation),below is code
var service = new google.maps.DirectionsService(), poly,snap_path=[];
poly = new google.maps.Polyline({ map: map });
for(j=0;j<snap_path_points.length-1;j++){
service.route({
origin: snap_path_points[j],
destination: snap_path_points[j+1],
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
snap_path = snap_path.concat(result.routes[0].overview_path);
poly.setPath(snap_path);
}
});
}
I divided my locations to batches of 8 and tried the same (i.e if 24 points use 3 for loops ) but i am getting OVER_QUERY_LIMIT.
i wonder how its working with event listener here.
OVER_QUERY_LIMIT indicates the webpage has sent too many requests
within the allowed time period.
Is there anyway to plot complete snap to road path with more than 8 points.
The problem is not that you sent too many points it is that you made too many request in the given time period. The snap to roads api states that:
Users of the standard API:
2,500 free requests per day and 10 requests per second
So if you sent more request than the limit described above, it is the reason why you are getting that error.