简体   繁体   中英

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?

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

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

Just use the js .includes function to simplify the answers already given.

let markerPositions = [];

Then before you add a new marker just do a test:

if (markerPositions.includes(Lat.toString() + "," + Lng.toString()))  {
    continue;
}

//logic here to create the actual google.Maps.Marker, add it to the map, etc.

markerPositions.push(Lat.toString() + "," + Lng.toString())

You can try using getVisible() method

var isVisible = marker.getVisible(); 
if ( isVisible && marker.getPosition() != myLatLng ) {
    marker.setPosition(myLatLng);
    marker.setVisible(true);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM