update google map route as user location change ionic 4 - google-maps

I am trying to build a live tracking with the route using Google Map JS version in ionic 4.
What I am trying to achieve is to give the route to the user from source to destination and update the route if the user chooses a new path other than the google provided one. The source is the user and destination is some point in the map.
I am able to draw route and update it if the user change the provided path using
startNavigation(){
this.geolocation.getCurrentPosition({ enableHighAccuracy: true })
.then((position) => {
this.userPosition = position;
this.userVehicleMarker = new google.maps.Marker({
map: this.map,
position: { lat: position.coords.latitude, lng: position.coords.longitude },
icon: this.vehicleIcon
});
this.addInfoWindow(this.userVehicleMarker, 'me')
this.watchVehicle = this.geolocation.watchPosition({ enableHighAccuracy: true })
.subscribe(async (pos) =>
{
// Calling the redraw function on every 25 meters distance travelled
this.drawRouteFromVehicleToDestination(pos.coords.latitude, pos.coords.longitude)
}
}, (err: PositionError) => {
// alert(err.message)
console.log("error : " + err.message);
});
})
)
drawRouteFromVehicleToDestination(lat, lng) {
let _self = this;
let directionsService = new google.maps.DirectionsService;
let directionsRenderer = new google.maps.DirectionsRenderer({
polylineOptions: {
strokeColor: "#428BE8",
strokeWeight: 2
},
suppressMarkers: true,
preserveViewport: true
});
directionsRenderer.addListener('directions_changed', function () {
let _data = directionsRenderer.getDirections();
let _newData = _data['routes'][0]['legs'][0]
console.log(_newData)
});
directionsService.route({
origin: { lat: lat, lng: lng},
destination: { lat: 27.673586, lng: 85.435131},
travelMode: 'DRIVING',
optimizeWaypoints: true,
provideRouteAlternatives: false,
avoidTolls: true,
}, (res, status) => {
if (status == 'OK') {
directionsRenderer.setDirections(res);
directionsRenderer.setMap(this.map);
} else {
console.warn(status);
}
});
}
But the issue is, it is sending a lot of requests to google API and which does not look like a practical approach to follow.
Is there any other approach I should follow using which I could track the route and update it as per user location change and also minimize the google ping?
Thank you in advance for your help.

I think the issue is that you call drawRouteFromVehicleToDestination() very frequently (every time the vehicle position changes, from this.geolocation.watchPosition). One way to reduce the number of calls would be to "debounce" this calls, limiting them to every X ms at most, since probably it's acceptable to update every 200/300 ms. For example, you could use the lodash _.debounce function. For an in-depth explanation, see also the article Debouncing and Throttling Explained Through Examples.
this.watchVehicle = this.geolocation.watchPosition({ enableHighAccuracy: true })
.subscribe(async (pos) => {
_.debounce(() => {
this.drawRouteFromVehicleToDestination(pos.coords.latitude, pos.coords.longitude);
}, 300, { leading: true });
}, (err: PositionError) => {
// alert(err.message)
console.log("error : " + err.message);
});

Related

Google Maps Autocomplete strictbounds parameter doesn't work

I have tryied to used Google Maps strictbounds parameter to restrict autocomplete results to an specific area. My current code is:
var autocomplete = new google.maps.places.Autocomplete(spaceAddress, { types: [ 'geocode' ], strictbounds: {location: "-23.544085,-46.7125434", radius: "12000"}, language: "pt-BR" });
Althoug it doesn't break my application, it also doesn't restrict the results to the selected area. Alternatively, I used the country restriction below, but the customer doesn't like it!
Here's the complete code in use by now:
document.addEventListener("DOMContentLoaded", function() {
var spaceAddress = document.getElementById('space_address');
if (spaceAddress) {
var autocomplete = new google.maps.places.Autocomplete(spaceAddress, { types: [ 'geocode' ], strictbounds: {location: "-23.544085,-46.7125434", radius: "12000"}, language: "pt-BR" });
google.maps.event.addDomListener(spaceAddress, 'keydown', function(e) {
if (e.key === "Enter") {
e.preventDefault();
const spaceAddress = document.getElementById('space_address').value;
if (spaceAddress != '' && spaceAddress != null) {
codeAddress(spaceAddress);
}
}
});
}
Could someone please enlighten me?!
You need to create a google.maps.Circle class first and then use that object to get the bounds via getBounds(). Also as mentioned already strictbounds is a boolean
https://developers.google.com/maps/documentation/javascript/reference/places-widget#Autocomplete
var circle = new google.maps.Circle({ center: new google.maps.LatLng(-23.544085, -46.7125434), radius: 12000 })
var autocomplete = new google.maps.places.Autocomplete(spaceAddress, { types: [ 'geocode' ], bounds: circle.getBounds(), strictbounds: true });
Unfortunately I can't comment yet, so a new answer. The answer from danbeggan works, but there is a tiny error in his code. The attribute is called strictBounds, here is the correct code:
var circle = new google.maps.Circle({ center: new google.maps.LatLng(-23.544085, -46.7125434), radius: 12000 })
var autocomplete = new google.maps.places.Autocomplete(spaceAddress, { types: [ 'geocode' ], bounds: circle.getBounds(), strictBounds: true });
Note: radius is in meter

Use numbers instead of alphabet for DirectionsRenderer api Markers

I successfully display my direction on the google map with markers but I'm having trouble to change the alphabet inside of markers to numbers.
My method looks like,
directionDisplay(direction) {
this.DirectionsRenderer = new google.maps.DirectionsRenderer({ preserveViewport: true });
this.DirectionsRenderer.setMap(this.props.map);
return this.DirectionsRenderer.setDirections(direction);
}
and using it
DirectionsService.route({
origin,
destination,
waypoints,
optimizeWaypoints: true,
travelMode: this.props.maps.DirectionsTravelMode.DRIVING
}, (result, status) => {
if (status == this.props.maps.DirectionsStatus.OK) {
this.directionDisplay(result);
} else {
console.error(`error fetching directions ${result}`);
}
});
I tried something like this.DirectionsRenderer = new google.maps.DirectionsRenderer({ preserveViewport: true, markerOptions: {label: '1'} }); but '1' just overlays on the alphabets instead of replacing them.
Does anyone know how to figure this out?
Thank you,

An elegant way to find shortest and fastest route in Google Maps API v3?

I am making a taxi fare calculator. One of the business requirements is that, the company wants the shortest and fastest route options. I know Google directionService by default searched for the fastest route. I set the "avoidhighways" option in request parameter to true in order to get the shortest route, but I am not quite happy with the result.
Anyone have a better solution than that??
To obtain the shortest route from A to B I would suggest to make different queries with the “alternatives=true” parameter, playing with the “avoid” parameter between avoid=toll, avoid=highways, and then I would compare all results to pick the shortest route.
directionsService = new google.maps.DirectionsService;
//avoiding tolls
directionsService.route({
origin: {
'placeId': originId
},
destination: {
'placeId': destinationId
},
provideRouteAlternatives: true,
avoidTolls: true,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
routesResponses.push(response);
}
else {
window.alert('Directions request failed due to ' + status);
}
});
//avoiding highways
directionsService.route({
origin: {
'placeId': originId
},
destination: {
'placeId': destinationId
},
provideRouteAlternatives: true,
avoidHighways: true,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
routesResponses.push(response);
}
else {
window.alert('Directions request failed due to ' + status);
}
//Results analysis and drawing of routes
var fastest = Number.MAX_VALUE,
shortest = Number.MAX_VALUE;
routesResponses.forEach(function(res) {
res.routes.forEach(function(rou, index) {
console.log("distance of route " +index+": " , rou.legs[0].distance.value);
console.log("duration of route " +index+": " , rou.legs[0].duration.value);
if (rou.legs[0].distance.value < shortest) shortest = rou.legs[0].distance.value ;
if (rou.legs[0].duration.value < fastest) fastest = rou.legs[0].duration.value ;
})
})
console.log("shortest: ", shortest);
console.log("fastest: ", fastest);
//painting the routes in green blue and red
routesResponses.forEach(function(res) {
res.routes.forEach(function(rou, index) {
new google.maps.DirectionsRenderer({
map:map,
directions:res,
routeIndex:index,
polylineOptions:{
strokeColor: rou.legs[0].duration.value == fastest? "red":rou.legs[0].distance.value == shortest?"darkgreen":"blue",
strokeOpacity: rou.legs[0].duration.value == fastest? 0.8:rou.legs[0].distance.value == shortest? 0.9: 0.5,
strokeWeight: rou.legs[0].duration.value == fastest? 9:rou.legs[0].distance.value == shortest? 8: 3,
}
})
})
})
});
}
}
You get three options with the alternatives=true option set. You can then search through those for both the shortest and fastest of the routes returned.
See http://codepen.io/jasonmayes/pen/DupCH.
var shortestDistance = function() {
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var size = 0;
var currentPosition;
// An array of interesting places we want to potentially visit.
var interestingPlaces = [
{'title': 'Regents Park', 'latLng': new google.maps.LatLng(51.530686, -0.154753)},
{'title': 'Hyde Park', 'latLng': new google.maps.LatLng(51.507293, -0.164022)},
{'title': 'Green Park', 'latLng': new google.maps.LatLng(51.504088, -0.141706)},
{'title': 'Regents Park', 'latLng': new google.maps.LatLng(51.479185, -0.159903)}
];
// An array to store results from Google routing API.
var routeResults = [];
// Call this upon page load to set everything in motion!
function initialize(currentLat, currentLng) {
currentPosition = new google.maps.LatLng(currentLat, currentLng);
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 13,
center: currentPosition
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
var marker = new google.maps.Marker({
position: currentPosition,
map: map,
title: 'Currrently location.'
});
var i = interestingPlaces.length;
while (i--) {
interestingPlaces[i].marker = new google.maps.Marker({
position: interestingPlaces[i].latLng,
map: map,
title: interestingPlaces[i].title,
icon: 'http://maps.google.com/mapfiles/ms/icons/green.png'
});
}
findNearestPlace();
}
// Loops through all inteesting places to calculate route between our current position
// and that place.
function findNearestPlace() {
var i = interestingPlaces.length;
size = interestingPlaces.length;
routeResults = [];
while (i--) {
calcRoute(interestingPlaces[i].latLng, storeResult);
}
}
// A function to calculate the route between our current position and some desired end point.
function calcRoute(end, callback) {
var request = {
origin: currentPosition,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
callback(response);
} else {
size--;
}
});
}
// Stores a routing result from the API in our global array for routes.
function storeResult(data) {
routeResults.push(data);
if (routeResults.length === size) {
findShortest();
}
}
// Goes through all routes stored and finds which one is the shortest. It then
// sets the shortest route on the map for the user to see.
function findShortest() {
var i = routeResults.length;
var shortestIndex = 0;
var shortestLength = routeResults[0].routes[0].legs[0].distance.value;
while (i--) {
if (routeResults[i].routes[0].legs[0].distance.value < shortestLength) {
shortestIndex = i;
shortestLength = routeResults[i].routes[0].legs[0].distance.value;
}
}
directionsDisplay.setDirections(routeResults[shortestIndex]);
}
// Expose the initialize function publicly as "init".
return {
init: initialize
};
}();
// Upon page load, lets start the process!
google.maps.event.addDomListener(window, 'load', shortestDistance.init(51.489554, -0.12969));
DISCLAIMER
THIS IS NOT MY PEN!!! I AM JUST REFERRING TO A USEFUL RESOURCE THAT MIGHT HELP
First of all, sorry for my solution being in TS, you can easily convert it to JS.
The "avoidhighways" attribute is not there to get the fastest or shortest route, it's there for what the name suggests, avoiding highways.
I've made my own solution by always getting multiple routs with this attribute:
directionsService.route({
[...]
provideRouteAlternatives: true
[...]
}, (response, status) => {
if (status === google.maps.DirectionsStatus.OK) {
var shortest: google.maps.DirectionsResult = this.shortestRoute(response);
this.directionsDisplay.setDirections(shortest);
[...]
And I made this function that returns the DirectionsResult with just the one route. In this case it's the shortest, but you can tweek it so it returns what ever route suits your needs.
shortestRoute = (routeResults: google.maps.DirectionsResult): google.maps.DirectionsResult => {
var shortestRoute: google.maps.DirectionsRoute = routeResults.routes[0];
var shortestLength = shortestRoute.legs[0].distance.value;
for (var i = 1; i < routeResults.routes.length; i++) {
if (routeResults.routes[i].legs[0].distance.value < shortestLength) {
shortestRoute = routeResults.routes[i];
shortestLength = routeResults.routes[i].legs[0].distance.value;
}
}
routeResults.routes = [shortestRoute];
return routeResults;
}
I took code from Soldeplata Saketos answer and edited it since it wasn't working. Added params so you can just call it with it like.
shortestRoute(origin, destination, map);
Works for me all though I'm not sure how correct it is.
Here:
function shortestRoute(origin, destination, map) {
directionsService = new google.maps.DirectionsService();
var routesResponses = [];
//avoiding tolls
directionsService.route({
origin: origin,
destination: destination,
provideRouteAlternatives: true,
avoidTolls: true,
travelMode: google.maps.TravelMode.DRIVING
}, function (response, status) {
if (status === google.maps.DirectionsStatus.OK) {
routesResponses.push(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
//avoiding highways
directionsService.route({
origin: origin,
destination: destination,
provideRouteAlternatives: true,
avoidHighways: true,
travelMode: google.maps.TravelMode.DRIVING
}, function (response, status) {
if (status === google.maps.DirectionsStatus.OK) {
routesResponses.push(response);
} else {
window.alert('Directions request failed due to ' + status);
}
//Results analysis and drawing of routes
var fastest = Number.MAX_VALUE,
shortest = Number.MAX_VALUE;
routesResponses.forEach(function (res) {
res.routes.forEach(function (rou, index) {
console.log("distance of route " + index + ": ", rou.legs[0].distance.value);
console.log("duration of route " + index + ": ", rou.legs[0].duration.value);
if (rou.legs[0].distance.value < shortest) shortest = rou.legs[0].distance.value;
if (rou.legs[0].duration.value < fastest) fastest = rou.legs[0].duration.value;
})
})
console.log("shortest: ", shortest);
console.log("fastest: ", fastest);
//painting the routes in green blue and red
routesResponses.forEach(function (res) {
res.routes.forEach(function (rou, index) {
new google.maps.DirectionsRenderer({
map: map,
directions: res,
routeIndex: index,
polylineOptions: {
strokeColor: rou.legs[0].duration.value == fastest ? "red" : rou.legs[0].distance.value == shortest ? "darkgreen" : "blue",
strokeOpacity: rou.legs[0].duration.value == fastest ? 0.8 : rou.legs[0].distance.value == shortest ? 0.9 : 0.5,
strokeWeight: rou.legs[0].duration.value == fastest ? 9 : rou.legs[0].distance.value == shortest ? 8 : 3,
}
});
});
});
});
}

Gmap3 applying a new center postion without destroying the whole map

I am hacking around with gmap3 managing to get the first task working. Showing the map using a lat long.
My javascript look likes
$('#map_canvas').gmap3(
{
action: 'init',
options: {
center: [x,y],
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControlOptions: {
mapTypeIds: []
}
}
},
{
action: 'addMarkers',
radius: 100,
markers: GetMarkers(),
clusters:
{
0:
{
content: '<div class="cluster cluster-3">CLUSTER_COUNT <div class="cluster-3text">Stops</div> </div>',
width: 66,
height: 65
}
},
marker:
{
options:
{
icon: new google.maps.MarkerImage('../img/marker.png', size, origin, null, null)
},
events:
{
mouseover: function (marker, event, data) {
getArrivalsAndStop(marker, event, data);
},
mouseout: function () {
$(this).gmap3({ action: 'clear', name: 'overlay' });
}
}
}
});
This loads the map how I want. My next step is to be able apply a new lat & long. How can I do this without destroying the whole map and recreating it everytime?
I am using jquery gmap3 plugin.
If you want to call setCenter after having initialized the map and without reloading the whole thing you can do this like this :
$('#mymap').gmap3('get').setCenter(new google.maps.LatLng(48.706685,-3.486694899999975))
$('#mymap').gmap3('get') is the magic thing here, it give you the real google map object I think.
It was hard for me to find this out so I hope it can help someone else.
From the documentation:
This example executes map.setCenter with the result of the address resolution, target is not specified because this is the map.
$('#test').gmap3(
{
action: 'getLatLng',
address: '2 bis rue saint antoine, eguilles',
callback: function(result){
if (result){
$(this).gmap3({action: 'setCenter', args:[ result[0].geometry.location ]});
} else {
alert('Bad address 2 !');
}
}
});
So it looks like if you know the coordinates and don't need to use the geocoder, it would be:
$(this).gmap3({action: 'setCenter', args:[ new google.maps.LatLng(latitude, longitude) ]});
Kind of late in the game, but I am using a list and map(google maps type). hope it helps
Here is how I achieved it
$(document).delegate('#inner_list li', 'click', function () {
var id = $(this).attr('data-id');
$("#map-canvas").gmap3({
get: {
name:"marker",
id: id,
all: true,
callback: function(objs){
$.each(objs, function(i, obj){
obj.setIcon("http://www.markericon.com");
var newLL = obj.getPosition()
$('#map-canvas').gmap3('get').panTo(newLL)
});
}
}
});
});

init gmap3 using geocode

I am new to gmap3, is it possible to init the gmap3 using a place address?
I know generally it is done with latitude and longitude.
I have done markers with this this location name using this example.
I have already gone through this example too, but no luck.
And also i need to zoom the places on selection, i use auto complete for this purpose.
My code is given below
$('#test').gmap3(
{ action:'init',
options:{
address: "kerala,india"
}
}
);
First use getLatLng() to retrieve the location, when successfull set the center:
$('#test1').gmap3(
{ action : 'getLatLng',
address:'kerala,india',
callback : function(result){
if (result){
$(this).gmap3({action: 'setCenter', args:[ result[0].geometry.location ]},
{action: 'setZoom', args:[ 12]});
} else {
alert('not found !');
}}});
var add="kerala,india";
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ address: add, region: 'no' },
function (results, status) {
if (status.toLowerCase() == 'ok') {
// Get center
var coords = new google.maps.LatLng(
results[0]['geometry']['location'].lat(),
results[0]['geometry']['location'].lng()
);
//alert(coords);
$map.gmap3("get").setCenter(coords);
$map.gmap3("get").setZoom(12);
addMarker(coords);
}
else {
alert("address not found");
}
}
function addMarker(marker) {
$map = $('#googleMap');
if (marker) {
$map.gmap3(
{ action: 'init',
options: {
center: eval(marker),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
},
{ action: 'addMarker',
latLng: eval(marker),
options: {
draggable: true,
icon: new google.maps.MarkerImage('http://maps.google.com/mapfiles/marker.png')
},
events: {
dragend: function (mark) {
updateMarker(mark);
}
}
});
}
}
Using above code you can get latitude/longitude also and drag searched location marker.
This feature will be in next version (5.0), current is not updated,
here is a working code :
$('#test1').gmap3({
action : 'getLatLng',
address:'kerala,india',
callback : function(result){
if (result){
$(this).gmap3({
action: "init",
options:{
center: result[0].geometry.location,
zoom: 12
}
});
} else {
alert('not found !');
}
}
});
notice, if your map is already initialized, you can use in the callback
$(this).gmap3("get").setCenter(result[0].geometry.location);
$(this).gmap3("get").setZoom(12);
You can use the following code as well:
var markerData = [];
markerData.push({ address: 'kerala,india', data: '' });
$('#test').gmap3({
action: 'addMarkers',
markers: markerData
}
);