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.
Related
I am using HERE for geocoding and generating heatmap.
Heatmap uses URL parameters but when there are many data points the URL can exceed 7.000 characters which is way over the browser limit of 2.048 which then throws a 400 error.
The heatmap works fine when there are fewer data points.
As is I send the URL to the front-end and render the returning image in the browser.
Is there a way I can use anything else than URL params? Or call the HERE endpoint directly from the server and return the actual image to the front-end? Or any other solution to 'fix' this?
I would prefer not to have to change map provider!
I'm using NestJS and Angular latest versions.
URL example (which is short enough to work just fine)
https://image.maps.ls.hereapi.com/mia/1.6/heat?apiKey=xxxxxxxxxxx&noblur=&w=2048&h=1024&a0=55.6059,12.99563&l0=2&rad0=1000&a1=55.61218,12.97896&l1=2&rad1=1000
Thank you
EDIT: I temporarily solved the issue by doing
if (this.heatUrl.length < 2000) {
this.heatUrl += (this.getParams(i, partLoc[i].coordinates, partLoc[i].weight));
};
This cuts ~100 data points of ~150 but since they are chronologically sorted that equals only 10-15% of the elements.
Still looking for a proper solution.
Regarding documentation on https://developer.here.com/documentation/map-image/dev_guide/topics/request-format.html - "Note: The method POST is not supported except for the route resource and it is limited to payloads of 8K maximum."
In this case you can achieve your target only to utilize JS API with a heat map using below code like:
// Create a provider for a semi-transparent heat map:
var heatmapProvider = new H.data.heatmap.Provider({
colors: new H.data.heatmap.Colors({
'0': 'blue',
'0.5': 'red',
'1': 'yellow'
}, true),
opacity: 0.7,
// Paint assumed values in regions where no data is available
assumeValues: false
});
// Add the data:
heatmapProvider.addData([
{lat: 52, lng: 13, value: 3},
{lat: 52, lng: 13.5, value: 1},
{lat: 52, lng: 14, value: 3}
]);
// Add a layer for the heatmap provider to the map:
map.addLayer(new H.map.layer.TileLayer(heatmapProvider));
Above example in JS Fiddle: https://jsfiddle.net/po5r0w3b/1/
Documentation: https://developer.here.com/documentation/maps/3.1.30.7/api_reference/H.data.heatmap.Provider.html
Other examples:
https://demo.support.here.com/examples/v3.1/heatmap
https://demo.support.here.com/examples/v3.1/geotag_screenshot
I'm trying to get an idea of the type of road returned in a Google Directions API call - either speed limit, type of road etc. You can get speed limit from Google Premium API if you pay. I'd rather find an alternative way.
In google maps you can style a map to colour the road types:
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: 'roadmap',
disableDefaultUI: false,
zoom: 13,
center: {lat: 52.2053, lng: 0.1218},
styles: [ {"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"color":"#00FF00"}]},
{"featureType":"road.arterial","elementType":"geometry.fill","stylers":[{"color":"#ff00ff"}]},
{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#ffff00"}]},
});
So, google maps has the information and can style a map accordingly. The Google Directions API does not return the road type (local/arterial/highway) or the speed limit.
Any ideas on how I can get the information?
Every time I try to get the new polygon when I edit it, either by dragend or click, I always get the initial paths of my variable.
I initialize my paths variable with:
paths: Array<LatLngLiteral> = [{lat: -12.052224, lng: -77.050342}, {lat: -12.064306, lng: -77.031790}, {lat: -12.075951, lng: -77.054554}, {lat: -12.063236, lng: -77.072506}, {lat: -12.052224, lng: -77.050342}];
Never update the paths variable whatever I do.
What am I failing? Why I can not get the final polygon with its respective paths and always get the initial? Or what is the correct way to get the new polygon?
This is my component:
<sebm-google-map [latitude]="lat" [longitude]="lng" [zoom]="zoom">
<sebm-map-polygon [paths]="paths" [editable]="true" [polyDraggable]="true" [strokeColor]="'#c60331'" (polyDragEnd)="onDragEnd($event, paths)">
</sebm-map-polygon>
</sebm-google-map>
Late but I thought someone like me may get some help so adding the answer.
The current release doesn't support it so you will need to make some changes to the current node_module. See this url:
https://github.com/SebastianM/angular-google-maps/pull/991
willshowell has explained what needs to be done.
Steps:
Update the sebm to agm (take the current release as of now)
Second, update your angular to at least 2.3 because it will not work with 2.0.
In the link above, he has committed various files to the branch. What he has done, is already explained in the issue.
Short explanation: he has changed the Array to MVCArray so you can get the exact data type which google uses for it's map paths, added getPath() and getPaths() functions. I did same for Polygons you can download the files here to see what I need to change for getting new Paths for Polygons after DragEnd Dropbox link for files changed in #agm module
Once you have made changes to Node Module, you can use the following code in the mouse up event of your PolyGon:
#ViewChildren(AgmPolygon)
polygonData: QueryList<AgmPolygon>;
polyMouseUp($event: any, index:number, polygon: any) {
var i =0;
this.polygonData.forEach(
x =>{
if(i==index){
x.getPath().then((y: any[]) => {
console.log('-');
y.forEach(z => console.log(z.lat(), z.lng()));
});
}
i++;
}
);
}
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
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)