JavaScript/Google Maps - map.fitBounds doesn't work - javascript

I am trying to fit the bounds of the map after drawing the route on Google Maps, for some reason the below does not get applied, it seems that it's ignored, I've even tried to set manual zoom, it was ignored too:
var bounds = response.routes[0].bounds;
this.map.fitBounds(bounds);
Here is the current result:
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({
origin: pickUp.formattedAddress,
destination: dropOff.formattedAddress,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
var bounds = response.routes[0].bounds;
this.map.fitBounds(bounds);
} else {
console.log('Directions request failed due to ' + status);
}
});
}

Related

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 - Passing google.maps.Place to Direction Service

According to the Google documnetation, one can pass the Google Place ID of a location to the Direciton Service. However, regardless of what combination I try, I absolutely cannot get it to work; I am receiving a NOT_FOUND error. I have tried hard coding the id as a test to no avail.
The basic initialization code:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var hotelMap;
var placesService;
function initialize() {
var mapOptions = {
center: { lat: 37.30138, lng: -89.57778},
zoom: 15,
};
hotelMap = new google.maps.Map(document.getElementById("googlemaps"), mapOptions);
var marker = new google.maps.Marker({
position:{ lat: 37.30138, lng: -89.57778},
map: hotelMap,
});
var info = new google.maps.InfoWindow({
content: "3265 William Street, Cape Girardeau, MO 63701"
});
marker.setMap(hotelMap);
info.open(hotelMap, marker);
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(hotelMap);
directionsDisplay.setPanel(document.getElementById("directionModalBody"));
document.getElementById("searchButton").addEventListener("click", function() {
var keyword = document.getElementById("searchBox").value;
var requestOptions = {
location: { lat: 37.3011339, lng: -89.5770238},
radius: '5000',
keyword: keyword
};
placesService = new google.maps.places.PlacesService(hotelMap);
placesService.nearbySearch(requestOptions, findCallback);
});
}; // end initiallize
The window.onload function:
window.onload = function() {
initialize();
document.getElementById("calcDirections").onclick = function() {
if ($("#city").val() != null && $("#city").val() != "") {
findRoute();
} else {
alert("Please Enter a City");
}
}; // end onclick
$(".areaList").on("click", "a", function(e) {
e.preventDefault();
var placeID = $(this).attr("href");
locationRoute(placeID);
}) // end onclick
};
The problem function:
function locationRoute(locationID) {
var start = "ChIJfbJ8AyaId4gR4XCrciru2Qc";
var end = new google.maps.Place(locationID);
alert(locationID);
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
}; // end request object
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
document.getElementById("getDirectionButton").click();
} else {
alert(status);
}// end if
}); // end route
} // end findRoute
I have tried just passing the place IDs as a string with no success. I have tried prefixing them, again no success. It seems from the Google documentation, one needs to create a google.maps.Place object, but how? I consulted the documentation (https://developers.google.com/android/reference/com/google/android/gms/location/places/Place#getId()), but did not see a constructor. How can I resolve this issue? Thanks so much.
Try this
directionsService.route({
origin: {placeId: start},
destination: {placeId: locationID}
...
There are two different options available
if you want to use place id
directionsService.route({
origin: {placeId: start},
destination: {placeId: locationID})
if you want to use lat and long
directionsService.route({
origin: {location: {lat:33.699234,lng:-102.870486}},
destination: {location: {lat:33.123366,lng:-102.862864}},
travelMode: "DRIVING"
and also make sure you configure direction service in google console
here is the link for that
https://developers.google.com/maps/documentation/javascript/directions

TypeError in JavaScript, Google Maps API

I'm currently developing a Webapps using the Google Maps API. I want to plot X different routes simultaneosly to the same destination location.
If I plot one, it works, but when I work with arrays (Because I don't know how many routes I will plot finally) it shows me this type of errors. The code when calculating the routes is like these.
var rendererOptions = [];
var directionsDisplay = [];
for (var k = 0; k < carLatLng.length; k++) {
rendererOptions[k] = {
map: map
};
directionsDisplay[k] = new google.maps.DirectionsRenderer(rendererOptions[k]);
var request = {
origin: carLatLng[k],
destination: place.geometry.location,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService = new google.maps.DirectionsService();
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay[k].setDirections(response);
} else alert('Failed to get directions');
});
}
The error tells me TypeError: directionsDisplay[k] is undefined. (It refers to the one inside the if() clause)
Hope guys you could help me. I have tried some options but none of them works. Only works when I eliminate the for loop (and the array-type)
Thank you
directionsService.route is asynchronous - by the time the last repsonse is received, the loop would've run it's course, and k == carLatLng.length - thus directionsDisplay[k] will be undefined
What you need is to change
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay[k].setDirections(response);
} else alert('Failed to get directions');
});
to something like
function(directionsDisplay) {
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else alert('Failed to get directions');
});
}(directionsDisplay[k]);
there's probably easier ways to make a closure, but my mind is addled at the moment
edit: for some clarity, maybe, hopefully -
function(captured_k) {
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay[captured_k].setDirections(response);
} else alert('Failed to get directions');
});
}(k);

Google Maps Api check if place is on the route

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()

Categories