remove route with google map - javascript

I got a small app that use the Direction Service feature of Google Map. It is working well, I can change routes, but I have a small problem, where a user could go back to a list of markers after tracing a route.
I can't find a way to delete routes with google map. For markers I store them and do setMap(null), do not see a way here...

You could also use:
directionsDisplay.setDirections({routes: []});
In this way, you can keep using one map with one renderer for all routes.

if you are using DirectionsRenderer to display the routes, you can call setMap(null) on it too. That way you delete the displayed route.
Using the example code here
http://code.google.com/apis/maps/documentation/javascript/examples/directions-simple.html
just call
directionsDisplay.setMap(null);

The other answers did not work for me. I found a solution from this question
define directionsDisplay only 1 time(outside of the click-handler)

This is the fix
// Clear past routes
if (directionsDisplay != null) {
directionsDisplay.setMap(null);
directionsDisplay = null;
}

Since on each call, new instance of DirectionRenderer created thats why each new instance is unaware of previous instance.
Move
var directionsDisplay = new google.maps.DirectionsRenderer();
to the global(at the top where all other Global variables have been initialized.)
By doing so, each time you would be using single instance of DirectionRenderer.

I had similar problem, I tried with directionsDisplay.setMap(null); but it didn’t work.
The problem was the directionsDisplay object which I created was declared locally.
I changed it to global and every time the function is called, it will use the same global directionsDisplay object and make changes to it. This will definitely remove the previous route displayed on same object.

set strokeWeight: 0 then polyline will hide

It's important - at least it was in my case - that while directionsDisplay can be declared globally the instance has to be created after the map object otherwise it gave a reference error
var map;
var directionsDisplay;
function initMap() {
map = new google.maps.Map(...);
directionsDisplay = new google.maps.DirectionsRenderer(...);
}
function yourFunction() {
// your code
directionsDisplay.addListener(...);
}

Related

Edit existing Google Maps element

For a website I'm using Google Maps to add polylines to a map to display a route. Some routes consist of multiple legs (stages) and I'm trying to add the polylines 'on request'. So only if a user chooses to show a leg, it will draw the polyline. Also the user might choose a completely different route and this new set of polylines should be drawn on the map as well.
My problem is that I can't seem to figure out or find how to select an existing map. I start out by creating a map using the following code:
qMap = new google.maps.Map(document.getElementById(mP.target), mapOptions);
mP.target contains a string with the canvas id and mapOptions is just a object with some options, nothing special.
So I do all kind of stuff with qMap, like adding markers, drawing polylines etc. And this shouldn't just be done at map initiation, but also when the user wants to add something. qMap isn't a global variable and I rather not have it being a global either.
I've tried qMap = google.maps.Map(document.getElementById(mP.target)) and other similar methods. With no success. I'm hoping you can help me out finding a way to this without global variables! Thanks!
There are a couple of things you could try.
1) Wrap your code in an immediately invoked function. This way any variables are contained within the function's scope and don't escape to pollute the global variable space which I guess is your main concern.
(function () {
var mapGlobal = new google.maps.Map(target, options);
function thatDoesSomething(){
// do something with mapGlobal
}
}());
2) Use a static object which might be handy for organising your code.
var Map = {
map: new google.maps.Map(target, options),
thatDoesSomething: function () {
// do something with this.map
}
};
3) Or combine them.
(function () {
var Map = {
map: new google.maps.Map(target, options),
thatDoesSomething: function () {
// do something with this.map
}
};
}());

Need to redraw a map with new data (in conjunction with CartoDB.js)

I seem to be having some trouble with reinitializing a Leaflet map object. I am running an init() function that starts by initializing a map, adding a tilelayer and layer with polygons, and then adding sublayers which color the polygons according to a ST_Intersects query. The issue is that this function is tied to an AJAX call that is caused by a click event but does not update the data according to the new parameters sent to the map. I don't think I am explaining this very well, so here is a bit of my code:
success: function(data) {
init(data);
}
function init(data){
// initiate leaflet map
alert("start");
var map = L.map('cartodb-map').setView([40.750028, -73.926768], 11);
alert("map made");
//create sublayers, etc
}
What happens is that the first time init is run, both 'start' and 'map made' alerts work, and the map is made according to the data. Any further calls to init simply alerts with "start" and "map made" is never alerted so I believe the problem is with reinitializing the leaflet map. What should I do to fix this?
Not sure the problem without seeing more of your code, but you could try calling map.remove(); the second time around. So:
if (map) {
map.remove();
// add in new map initialization here
} else {
var map = ...
}

Move marker dynamically

I am using Openlayers.Layer and OpenLayers.Marker to display a marker on the map.
It is positioned correctly and I can successfuly show it and hide it doing:
marker.display(boolean);
But I try to change its position before displaying it but with no success. I already tried this:
var projections = {
g: new OpenLayers.Projection("EPSG:4326"),
p: new OpenLayers.Projection("EPSG:900913")
};
var newlonlat = new OpenLayers.LonLat(newlon, newlat).transform(projections.g, projections.p);
marker.lonlat = newlonlat
layer.redraw();
(no errors triggered but position does not change)
and also tried this:
var px = map.getPixelFromLonLat(newlonlat);
marker.moveTo(px);
layer.redraw();
(it throws an error inside getPixelFromLonLat function. Error: c is null)
Why can't I move markers dynamically and what is the best way to do it?
Edit:
Maybe the problem resides in my position projection transformation when using second option:
new OpenLayers.LonLat(newlon, newlat).transform(projections.g, projections.p);
Edit 2
So, going deeper I found that marker.map property was null, so after its initialization I did:
var marker = new OpenLayers.Marker(lonlat, icon);
marker.map = map;
where map is an OpenLayers.Map object and now its working fine. Don't know why but it fixed it.
marker.moveTo works fine for me:
var px = map.getPixelFromLonLat(new OpenLayers.LonLat(newLon,newLat));
marker.moveTo(px);
Hope this helps :-)
To workaround the problem I did:
marker.lonlat = new OpenLayers.LonLat(newlon, newlat);
layer.removeMarker(marker);
layer.addMarker(marker);
layer.redraw();
It seems stupid removing and adding the same marker to just update its position but it works. It may be slower when doing this to a large group of markers though.
Try:
marker.lonlat = new OpenLayers.LonLat(newlon, newlat);
layer.drawMarker(marker);
(not testet)

Adding Geolocation to Google Places Library

We're trying to build an app that allows users to view places around their current location.
You can see the Google Maps API & the Google Places Library functioning here, but not as one: http://www.blazingsasquatch.com/geo/index4.html
You'll notice the button "show me my loc" pulls your current location and the map is showing an arbitrary location in Boston with places nearby.
We've created variables for both the longitude and latitude and we've attempted to pass those variables directly into the "pyrmont" location variable but we've had no luck.
Initially we tried setting the "pyrmont" location using following, also with no luck:
google.maps.LatLng(position.coords.latitude, position.coords.longitude);
So how can we get the current location populated?
var pyrmont = new google.maps.LatLng("CURRENT LOCATION HERE");
Will it accept a variable or an integer only?
initialize will be called before the callback of navigator.geolocation.getCurrentPosition() , so you cannot use the result in initialize() .(you may view getCurrentPosition as a asynchronous request)
Invoke the action(creation of the marker and places-request) inside the callback of getCurrentPosition()
See a working demo: http://jsfiddle.net/doktormolle/C5ZtK/
The LatLng constructor takes two floating point numbers, like so:
pos = new google.maps.LatLng(-34.397, 150.644);
After reviewing the source code, it seems the problem is another one: the anonymous callback function you are passing to getCurrentPosition() is called when the geographic location is found, which can take some time (especially using GPS and such). initialize() is called when the page is loaded, which is sooner, so place is not set at this time (besides, it's not visible in initialize() since it's not a global variable, but never mind that). So you have to move the stuff you're currently doing in initialize() to the callback function you are passing to getCurrentPosition(). Then, you can use
var pyrmont = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

Removing routes rendered on a Google Map

I'm trying to do something that I gather has been done quite a few times before, although I'm having some difficulty accomplishing it.
I have a webpage that displays three Google Maps.
For each of these google maps, I have a text box that accepts a post code / zip code, and a "get directions" button.
Clicking on each of these buttons uses the google.maps.DirectionsService object to display ONE set of directions in ONE panel centered at the bottom of the page.
My issue arises when I try to find a new route by searching again. As you can see in the image below, both routes are rendered.
I have one marker at the end which is in a markers collection.
I've read a few times now about how you can loop through this array and use marker.setMap(null) to clear this marker.
However, I can't seem to clear the actual routes after each specific search.
Has anybody had any problems with clearing markers from multiple maps?
Do you have to totally reset the map in some way?
If you have to clear markers, at what point in the lifecycle of the process should you do it so that your new journey appears after the search, but the old one is removed?
I use the same google.maps.DirectionsService object for all three Google maps, and they all call the same method to calculate directions, but passing in their own map object as a parameter.
function calcRoute(startPoint, location_arr) {
// Create a renderer for directions and bind it to the map.
var map = location_arr[LOCATION_ARR_MAP_OBJECT];
var rendererOptions = {
map: map
}
if(directionsDisplay != null) {
directionsDisplay.setMap(null);
directionsDisplay = null;
}
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
The gist being that if directionsDisplay != null, we not only pass null to setMap, we also nullify the whole object afterweards, and I found this fixed it.
I dont know the answer.... most likely all u need to do is depending on circumstances:
// put the codes after direction service is declared or run directionsService //
directionsDisplay.setMap(null); // clear direction from the map
directionsDisplay.setPanel(null); // clear directionpanel from the map
directionsDisplay = new google.maps.DirectionsRenderer(); // this is to render again, otherwise your route wont show for the second time searching
directionsDisplay.setMap(map); //this is to set up again
This is the only part you need:
// Clear past routes
if (directionsDisplay != null) {
directionsDisplay.setMap(null);
directionsDisplay = null;
}
This works for me
// on initiate map
// this listener is not necessary unless you use listener
google.maps.event.addListener(directionsRenderer, 'directions_changed', function () {
if(directionsRenderer.directions === null){
return;
}
// other codes
});
// on clear method
directionsRenderer.set('directions', null);

Categories