Remove rendered direction routes on google map - javascript

I try to render direction route on google map and my issue was, when I am try to get another direction route previously rendered route not clear. I want to know how I reset rendered route on the map.
Here my code.
function direction(dest, lat, lng) {
$('#direction').slideUp();
$('#results').slideDown();
$('#dest-direction').val(dest);
$('#direction-form').submit(function () {
var ori = $('#origin-direction').val();
map.setZoom(7);
var currentLatLng = new google.maps.LatLng(lat, lng);
map.setCenter(currentLatLng);
var directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setMap(map);
directionsRenderer.setPanel(document.getElementById('direction'));
var directionsService = new google.maps.DirectionsService();
/////////////////////
default_unit_system = google.maps.UnitSystem.METRIC;
if (current_unit == "km") {
default_unit_system = google.maps.UnitSystem.METRIC;
} else if (current_unit == "miles") {
default_unit_system = google.maps.UnitSystem.IMPERIAL;
}
/////////////////////
var request = {
origin: ori,
destination: lat+','+lng,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
unitSystem: default_unit_system
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsRenderer.setDirections(response);
} else {
//alert('Error: ' + status);
$('#direction').append('<table width="100%"><tr><td>Direction not found. Please try again.</td></tr></table>');
}
});
$('#direction-form').nextAll().remove();
return false;
});
}

I agree with Dr.Molle .
Still, One thing that can be useful for many overlays (like markers, like infowindows, ...): Store the objects in an array;
if needed, keep that array on the global scope;
then you can easily remove them from the map.
var renderObjects = [];
function clearRenderObjects() {
for(var i in renderObjects) {
renderObjects[i].setMap(null);
}
}
$('#direction-form').submit(function () {
// clear previous
clearRenderObjects();
...
var directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setMap(map);
// add to the array
renderObjects.push(directionsRenderer);
...
});

Use the same DirectionsRenderer-instance for all requests(currently you create a new instance on each request)

Related

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

how to turn a function into angular scope function

i've a code like below for calculate distance between two points, this is a code for my ionic project. i used Angularjs-google-maps by allenhwkim, and i want to turn the code into angular scope function so it can run on my View. by the way i get this code from my last question in this forum.
for calculate the distance :
var calcRoute = function(origin,destination,cb) {
var dist;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
var request = {
origin:origin,
destination:destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
cb(null, response.routes[0].legs[0].distance.value / 1000);
}
else {
cb('pass error information');
}
});
};
code below for running the function and hold the result in $scope.A so i can call the result by typing {{A}} on my View
calcRoute("-7.048443, 110.441022","-7.048264, 110.440388", function (err, dist) {
if (!err) {
$scope.A = dist;
}
});
the problem is, i just can use the function inside my controller and send the result with $scope, but how to turn the code for example to {{ calc(ori,dest) }} and return the distance in my View.
i've tried to do like this :
$scope.calc = function(ori,dest){
var calcRoute = function(origin,destination,cb) {
var dist;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
var request = {
origin:origin,
destination:destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
cb(null, response.routes[0].legs[0].distance.value / 1000);
}
else {
cb('pass error information');
}
});
};
calcRoute(ori,dest, function (err, dist) {
if (!err) {
return dist;
}else{
console.log("failed");
}
});
return calcRoute();
};
and call the function inside my View like this :
{{calc("-7.048443, 110.441022","-7.048264, 110.440388")}}
it's not working,
return undefined and show console error below :
Error: [$interpolate:interr] Can't interpolate:
{{calc("-7.048443, 110.441022","-7.048264, 110.440388")}}
InvalidValueError: in property origin: not a string; and not a LatLng or LatLngLiteral: not an Object
hope anyone can help me,thanks :))
Not sure you can compute the function on the fly and print the return value.
What you can do is:
Bind your function to a scope function $scope.calc = function(x,y){...}
inside do the usual assignment $scope.A = dist .
In the view just print {{A}}.
To call the function simply use calc(ori,dest). (from your code I didn't get where you should call it).
The error you mentioned is that you are calling calcRoute twice, once with parameters, and once without:
calcRoute(ori,dest, function (err, dist) {
if (!err) {
return dist;
}else{
console.log("failed");
}
});
return calcRoute();
The bigger problem is that you are not going to be able to evaulate your distance this way. Check out this SO post on evaluating asynchronous expressions.
Infinite loop with Angular expression binding
You're going to have to bind your values to $scope. If you're worried about cluttering up your controller with tons of $scope variables you could make an array and add multiple values to it, then use an ng-repeat to display the information in the view.

Google Maps API, Setting a name of marker when getting directions

I have a program that allows the user to select multiple items for a trip. Part of the program maps the items in google maps. I am using the lat/long coordinates to generate the waypoints and then the API takes it from there. The final map shows the route and markers. I would like to give each marker a custom name instead of the default street address currently being displayed. Is this possible?
//Display the route on the map
$.post("processors/getMapWayPoints.php",{
tripID: tripID
}, function(e){
console.log("Return is " + e);
latlong = JSON.parse(e);
//iterate through each locations lat/long and add it to the mappoints array for the route plotting
for(var i = 0; i < latlong.length; i+=3){
var name = latlong[i];
var lat = latlong[i+1];
var lng = latlong[i+2];
//create google lat/long point object
var pt = new google.maps.LatLng(lat, lng);
//add the location to the array for the route
mappoints.push({location:pt, stopover:true});
//not being used yet
pointNames.push(name);
}
var mapOptions = {
zoom:11,
center: home
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
directionsDisplay.setMap(map);
var request = {
origin:home,
destination:home,
waypoints: mappoints,
//optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
});

How to wait for Direction Service to complete to access Direction property of Direction Display

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
}
});

JavaScript Objects - Object values getting undefined after constructing

I am trying to create an object that handles Google Maps Api as following:
function GoogleMap(container, mapOptions) {
this.Container = container;
this.Options = mapOptions;
this.Map = new google.maps.Map(document.getElementById(this.Container), this.Options);
// Direction
this.DirectionService = new google.maps.DirectionsService();
this.DirectionRenderer = new google.maps.DirectionsRenderer();
this.DirectionRenderer.setMap(this.Map);
this.DirectionId = 0;
this.DirectionResponse = new Array();
this.DrawDirectionDriving = drawDirectionDriving;
}
and the drawDirectionDriving function is like this:
function drawDirectionDriving(start, end) {
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
this.DirectionService.route(request,
function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
this.DirectionRenderer.setDirections(response);
this.DirectionResponse[this.DirectionId] = response;
this.DirectionId++;
}
else {
alert("Error during drawing direction, Google is not responding...");
}
}
);
}
and in somewhere, I am using the object like this:
var myGoogleMap;
function MapInit() {
myGoogleMap = new GoogleMap("divMap", myMapOptions);
myGoogleMap.DrawDirectionDriving("İstanbul", "Ankara");
}
The Google Map is shown on my browser, there is no problem in constructing the object but error in DrawDirectionDriving function.
When I create a breakpoint on this line: " myGoogleMap.DrawDirectionDriving("İstanbul", "Ankara");" the "DirectionRenderer" seems constructed, but after this line (after the "Draw" method) the DirectionRenderer object seems null (undefined) so it outs en error like this "couldn't get setDirections properties it is null bla bla..."
Could you please give me a hand?
Thanks in advance...
The this keyword does point to something else in the route callback function. It's DirectionRenderer property resolves to null/undefined, and getting the setDirections property from that will cause the exception.
Use a dereferencing variable:
function drawDirectionDriving(start, end) {
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
var that = this;
this.DirectionService.route(request,
function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
that.DirectionRenderer.setDirections(response);
that.DirectionResponse[this.DirectionId] = response;
that.DirectionId++;
// ^^^^ points to the GoogleMap instance
}
else {
alert("Error during drawing direction, Google is not responding...");
}
}
);
}

Categories