Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a marker already exists or not in Google maps?

I have latitude and longitude of a place. I want to check whether such a marker is already present or not. How can I do it?

var myLatLng = new google.maps.LatLng(Lat, Long);
//before setting marker i want to check here
marker.setPosition(myLatLng);
marker.setVisible(true);

Is it possible?

like image 932
JIKKU Avatar asked Oct 15 '13 06:10

JIKKU


People also ask

How do I find the marker ID on Google Maps?

getId() function to retrieve marker id.

How many markers can Google Maps handle?

Answers. you can add 200 markers at a time but if you are using google service it will not response more than 10 or 20 at a time and if you have array of collection Lattitude and longitude just try to modify above code.


2 Answers

Whenever you add a marker to the map (it's also best to add the markers to an markers array at this point), add the lat and lng to a separate lookup array.

var lookup = [];
lookup.push([lat, lng]);
marker.setPosition(myLatLng);

Then when you want to check to see if a marker is present at a particular location, loop through the lookup array:

var search = [51.5945434570313, -0.10856299847364426];

function isLocationFree(search) {
  for (var i = 0, l = lookup.length; i < l; i++) {
    if (lookup[i][0] === search[0] && lookup[i][1] === search[1]) {
      return false;
    }
  }
  return true;
}

isLocationFree(search);
like image 153
Andy Avatar answered Sep 20 '22 19:09

Andy


Try this:

// mkList = [mark1, mark2, ...], existing marker container

var myLatLng = new google.maps.LatLng(Lat, Long);

// check if this position has already had a marker
for(var x = 0; x < mkList.length; x++) {
    if ( mkList[x].getPosition().equals( myLatLng ) ) {
        console.log('already exist');
        return;
    }
}

var newMarker = new GoogleMap Marker - by myLatLng;
mkList.push(newMarker);
  • Google map LatLng object has a method equals() to tell if a LatLng is equals to the other one
  • Google map Marker object has a method getPosition() which returns a LatLng object
  • user marker.getPosition().equals( myLatLng ) to tell is their position are the same

Link: https://developers.google.com/maps/documentation/javascript/reference#Marker

like image 42
Lyfing Avatar answered Sep 19 '22 19:09

Lyfing