I'm using the Google Direction Service to retrieve the lat+lng of the route, then pass the latlon to a php file and return markers via a xml file.
This all works fine, apart from I cant clear the old markers when I request a new route. The code below shows how I get the markers from the xml file, using jQuery. And the code underneath that shows the function I'm trying to use to clear the route (that works) and the old markers (that does not!)
Many thanks for any help.
//RETURN DATA FOR PLACE MARKERS
jQuery.get("MYXMLFILE", function(data) {
jQuery(data).find("marker").each(function() {
var eachMarker = jQuery(this);
var markerCoords = new google.maps.LatLng(
parseFloat(eachMarker.find("Lat").text()),
parseFloat(eachMarker.find("Lng").text())
);
var header = eachMarker.find("title").text();
var content = eachMarker.find("Content").text();
var wxicon = eachMarker.find("icon").text();
//---------------------------------------------
var marker = new google.maps.Marker({
position: markerCoords,
map: map,
icon: wxicon,
animation: google.maps.Animation.DROP,
title: header,
});
gmarkers.push(marker); // store the reference
});
});
//CLEAR OLD ROUTE + CLEAR MARKERS
function deleteOverlays() {
directionsDisplay.setDirections({routes: []});
gmarker.setMap(null);
gmarkers = [];
}
var markersArray = [];
Every time your create a marker add it to markerArray
for (i = 0; i < locations.length; i++) {
marker[i] = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
icon: icoImg,
map: map,
shadow: flagIcon_shadow,
title: locations[i][0]
});
markersArray.push(marker[i]);
}
After call deleteOverlays() to delete all maker from map.
// Deletes all markers in the array by removing references to them
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
in your case use this
function deleteOverlays() {
if (gmarkers) {
for (i in gmarkers) {
gmarkers[i].setMap(null);
}
gmarkers.length = 0;
}
}
Related
I'm using the lastest version of google maps, and trying to print the markers in the map.
To do that, I'm using:
function initmap2() {
map2 = new google.maps.Map(document.getElementById('map-scan'), {
zoom: 16,
styles: style,
center: { lat: 13.7218501, lng: -89.2039192 }
});
for (i = 0; i < positions.length; i++) {
markers = new google.maps.Marker({
position: new google.maps.LatLng(positions[i]),
map: map2
});
}
var markers = positions.map(function (location, i) {
return new google.maps.Marker({
position: location,
});
});
for (var i = 0; i < markers.length; i++) {
markers[i].info = new google.maps.InfoWindow({
content: '<b>' + positions[i]["title"].toUpperCase() + '</b>'
});
markers[i].info.open(map2, markers[i]);
}
}
The markers are displayed in the right position, but the InfoWindws are very distanced of them.
Why I'm using map2 instead of map. I have preloaded another googlemap and the map2 is loaded in a dialog (on demand, when the dialog is open)
How to fix this behavior?
Your problem is this... you loop over positions, creating a marker for each of your positions:
for (i = 0; i < positions.length; i++) {
markers = new google.maps.Marker({
position: new google.maps.LatLng(positions[i]),
map: map2
});
}
You then do the same thing again:
var markers = positions.map(function (location, i) {
return new google.maps.Marker({
position: location,
});
});
And at the end of this 2nd way of doing it, markers is an array of markers. Which you then loop over to setup the infowindows.
However, the first time you created the marker, you specified the map attribute. So those markers show up on the map.
The second time you didn't bother, so these markers aren't on the map.
You've got markers visible thanks to your first way of doing it. But then you're attaching the infowindows to the non-visible markers created the second way! :-/
The code's a bit of a mess, you can do it all in just the one loop over positions, and make sure you specify the map property for each marker. I'd just do:
var markers = [];
for (i = 0; i < positions.length; i++) {
markers.push(new google.maps.Marker({
position: new google.maps.LatLng(positions[i]),
map: map2
}));
markers[i].info = new google.maps.InfoWindow({
content: '<b>' + positions[i]["title"].toUpperCase() + '</b>'
});
markers[i].info.open(map2, markers[i]);
}
I am having lots of trouble trying to clear the markers. When the user zooms the map out beyond certain point. However I was unable to remove the marker. Here is what I have tried so far.
var zoomLevel = map.getZoom();
var ZoomMarker;
google.maps.event.addListenerOnce(map, 'mousemove', function() {
google.maps.event.addListener(map, 'zoom_changed', function() {
zoomLevel = map.getZoom();
if (zoomLevel >= 15) {
for (var i = 0; i < Zoomed_in.length; i++) {
ZoomMarker = new google.maps.Marker({
animation: google.maps.Animation.DROP,
position: new google.maps.LatLng(Zoomed_in[i][1], Zoomed_in[i][2]),
map: map,
});
}
zoomLevel = map.getZoom();
} else {
for (var i = 0; i < ZoomMarker.length; i++) {
ZoomMarker[i].setMap(null);
ZoomMarker.pop();
}
}
});
});
I don't want to make a global function for removing all markers since I have other markers which are called on map initialisation. I have tried to use https://developers.google.com/maps/documentation/javascript/examples/marker-remove
to remove the markers, however it does not seem to work. I presume this is due to the markers being in an array. This is why I am using the for loop to on the removal of the array.
Is there a way I can do:
ZoomMarker= new Object();
To destroy the array in effect removing it.
This functionality isn't creating an array it is just overwriting the ZoomMarker object.
ZoomMarker = new google.maps.Marker({
animation: google.maps.Animation.DROP,
position: new google.maps.LatLng(Zoomed_in[i][1], Zoomed_in[i][2]),
map: map,
});
Instead try this :
ZoomMarker.push( new google.maps.Marker({
animation: google.maps.Animation.DROP,
position: new google.maps.LatLng(Zoomed_in[i][1], Zoomed_in[i][2]),
map: map,
});
// assuming you make ZoomMarker = [];
EDIT:
I mentioned you need to make ZoomMarker an Array thats why push doesn't work.
var ZoomMarker = [];
This is exactly how the example is set that you cited.
var markers = [];
I don't seem to be able to make Google Maps click event listeners for markers to work. The only detail is that this is being run in a cycle, meaning that in the first time i include the map and run the add markers and their event listeners, the following times I have a function that only adds the markers and the listeners.
This is my initialize function and datasetRealtime is the array of markers:
function initialize() {
var mapOptions = {
zoom: 14,
scaleControl: true,
scaleControlOptions: {
position: google.maps.ControlPosition.TOP_LEFT
},
/* Map Zoom */
center: new google.maps.LatLng(41.186968, -8.697792),
/*Center Coordinate*/
mapTypeId: google.maps.MapTypeId.ROADMAP
}
realtime_map = new google.maps.Map(document.getElementById("map-canvasBig"), mapOptions);
for (var i = 0; i < datasetRealtime.length; i++) {
var latitude = parseFloat(datasetRealtime[i]["latitude"]);
var longitude = parseFloat(datasetRealtime[i]["longitude"]);
var myLatlng = new google.maps.LatLng(latitude, longitude);
var marker = new google.maps.Marker({
position: myLatlng,
map: realtime_map,
title: 'Just some title'
});
google.maps.event.addListener(marker, 'click', function () {
console.log("it worked")
});
}
}
And I am loading it with:
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=mykeygoeshere&sensor=false&callback=initialize";
document.body.appendChild(script);
This is the function that adds the markers and listeners if the map is already loaded:
function addMarkers(){
for (var i = 0; i < datasetRealtime.length; i++) {
var latitude = parseFloat(datasetRealtime[i]["latitude"]);
var longitude = parseFloat(datasetRealtime[i]["longitude"]);
var myLatlng = new google.maps.LatLng(latitude, longitude);
var marker = new google.maps.Marker({
position: myLatlng,
map: realtime_map,
title: 'Just some title'
});
google.maps.event.addListener(marker, 'click', function () {
console.log("it worked")
});
}
}
Update
I am cleaning the markers before I add the new ones with:
function clearOverlays(datasetRealtime) {
for (var i = 0; i < datasetRealtime.length; i++) {
datasetRealtime[i].setMap(null);
}
datasetRealtime = [];
}
I've tried so many ways, even with closures and I don't seem to be able to make it work. The markers are added, but there's no handler when I click on them (the little hand stays wide open)
The proble might be you are rewriting marker at each for loop.
You have to store your markes in a markersArray object.
Your code will look something like this:
var markers = [];
function addMarkers(){
for (var i = 0; i < datasetRealtime.length; i++) {
var latitude = parseFloat(datasetRealtime[i]["latitude"]);
var longitude = parseFloat(datasetRealtime[i]["longitude"]);
var myLatlng = new google.maps.LatLng(latitude, longitude);
var marker = new google.maps.Marker({
position: myLatlng,
map: realtime_map,
title: 'Just some title'
});
google.maps.event.addListener(marker, 'click', function () {
console.log("it worked")
});
markers.push(marker);
}
}
That might work!
May I suggest to you a code refactoring: since you have already an addMarkers method it could be simplier to call it in your initialize method than to rewrite the same code there.
Hi the below code will do for marker click also added a small code.. sry could'nt look into ur code fully still provided info that would help in solving..
var marker = new GMarker(location);
GEvent.addListener(marker, "click", function() {
alert('it works');
});
map.addOverlay(marker);
so i works in a geolocation project(asp.net MVC4), i have many positions in my database and i want to show it in my map, my problem that the script just show the first position, this is my script:
var checkpoints = [];
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++)
{
var place = locations;
for (var i = 0; i < place.length; i++)
{
var points = new google.maps.LatLng(place[i][1], place[i][2]);
checkpoints.push(points);
}
var check = checkpoints[0];
var index = 0;
for (var j = 0; j < checkpoints.length; j++)
{
check = checkpoints[j];
index = j;
var myLatLng = new google.maps.LatLng(place[index][1], place[index][2]);
var marker = new google.maps.Marker
(
{
position: myLatLng,
map: map,
title: place[index][0],
zIndex: place[index][3]
}
);
}
}
return marker;
}
so please if someone have any solution or idea i will be very appreciate.
Thanks everyone #david #Beetroot-Beetroot #razzak my script works fine now, this is my new script :
var checkpoints = [];
function setMarkers(map, locations) {
for (var i in locations) {
var points = new google.maps.LatLng(locations[i][1], locations[i][2]);
checkpoints.push(points);
var marker = new google.maps.Marker({
map: map,
position: points,
title: locations[i][0],
zindex: locations[i][4]
});
}
}
Update :
my script works fine but i have a small problem in my event, when i dblclick on a marker it should show his title but it just show me the title of the last marker :
var checkpoints = [];
function setMarkers(map, locations) {
for (var i in locations) {
var points = new google.maps.LatLng(locations[i][1], locations[i][2]);
checkpoints.push(points);
var marker = new google.maps.Marker({
map: map,
position: points,
title: locations[i][0],
zindex: locations[i][4],
});
//this is my event
google.maps.event.addListener(marker, 'dblclick', function () {
alert("I am marker " + marker.title);
});
}
}
I have simplified your code
function setMarkers(locations) {
for(var i in locations) {
var points = new google.maps.LatLng(locations[i][1].lat,locations[i][2].lng);
checkpoints.push(points);
var marker = new google.maps.Marker({
map:map,
position: points,
icon: 'myicon.png',//
title: locations[i][0],
zindex: locations[i][4]
});
}
}
Mohammadov, you are making it more complicated than it needs to be.
Try this :
function setMarkers(map, locations) {
for(var i=0; i<locations.length; i++) {
var loc = locations[i];
loc[4] = new google.maps.Marker({
position: new google.maps.LatLng(loc[1], loc[2]),
map: map,
title: loc[0],
zIndex: loc[3]
});
}
}
The map should then show the markers, and each member of the locations array should be augmented with a reference to its marker, as element [4].
the two loops inside the main loop are causing problems, they are unnecessary and can be avoided. also return marker at the end of the loop will return only the last one, you can remove it as well:
var checkpoints = [];
function setMarkers(map, locations) {
for (var i=0; i<locations.length; i++)
{
var place = locations[i],
myLatLng = new google.maps.LatLng(place[1], place[2]),
marker = new google.maps.Marker
(
{
position: myLatLng,
map: map,
title: place[0],
zIndex: place[3]
}
);
checkpoints.push({"point": myLatLng, "marker": marker});
}
}
The checkpoints now should have an array of LatLng and marker of each place.
jsfiddle
Im using the following code and trying to figure out how to add a function I can call that will remove the previous marker before adding a new one. the map uses onclick events to add marker where the user clicks... basically i only want one marker on the map at any given time.
i've searched and tried almost everything but must be doing it wrong somehow... please give the code a quick glance and let me know how it would be achieved.
thanks a million!
<script>
function initialize() {
var mapOptions = {
zoom: 11,
center: new google.maps.LatLng(document.getElementById('field_lat').value,document.getElementById('field_lng').value),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
google.maps.event.addListener(map, 'click', function(e) {
// SET MY UI SEARCH TEXT FIELDS TO THE LAT AND LNG
document.getElementById('field_lat').value = e.latLng.lat();
document.getElementById('field_lng').value = e.latLng.lng();
placeMarker(e.latLng, map);
});
}
function placeMarker(position, map) {
//Marker.setMap(null);
var Marker = new google.maps.Marker({
position: position,
map: map
});
map.panTo(position);
$("#listbox ul").empty();
docall();
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
the map is in the body as follows
<div id="map_canvas" style="width: 400px; height: 400px;"></div>
I tried to try to get this or something similar to work but no dice...
// Deletes all markers in the array by removing references to them
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
Just remove the previous marker if there is one.
var Marker;
function placeMarker(position, map) {
if(typeof marker!= 'undefined')
marker.setMap(null);
var Marker = new google.maps.Marker({
position: position,
map: map
});
map.panTo(position);
$("#listbox ul").empty();
docall();
}
Simply do the following:
I. Declare a global variable:
var markersArray = [];
II. Define a function:
function clearOverlays() {
for (var i = 0; i < markersArray.length; i++ ) {
markersArray[i].setMap(null);
}
}
OR
google.maps.Map.prototype.clearOverlays = function() {
for (var i = 0; i < markersArray.length; i++ ) {
markersArray[i].setMap(null);
}
}
III. Push markers in the 'markerArray' before calling the following:
markersArray.push(marker);
google.maps.event.addListener(marker,"click",function(){});
IV. Call the function wherever required.
clearOverlays();
OR
map.clearOverlays();
That's it!!
Hope that will help you.
Source: Google Maps API v3: How to remove all markers?
You can set the marker on first click and then just change the position on subsequent clicks.
var marker;
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
function placeMarker(location) {
if (marker == null) {
marker = new google.maps.Marker({
position: location,
map: map
});
} else {
marker.setPosition(location);
}
}