javascript 如何检查谷歌地图中是否已经存在标记?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19374833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:21:54  来源:igfitidea点击:

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

javascriptgoogle-mapsgoogle-maps-api-3

提问by JIKKU

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?

是否可以?

回答by Andy

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.

每当您向地图添加标记时(此时最好将标记添加到标记数组),请将 lat 和 lng 添加到单独的查找数组。

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

回答by lyfing

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 LatLngobject has a method equals()to tell if a LatLngis equals to the other one
  • Google map Markerobject has a method getPosition()which returns a LatLngobject
  • user marker.getPosition().equals( myLatLng )to tell is their position are the same
  • 谷歌地图LatLng对象有一个方法equals()来判断一个LatLng是否等于另一个
  • 谷歌地图Marker对象有一个getPosition()返回LatLng对象的方法
  • 用户marker.getPosition().equals( myLatLng )要告诉的是他们的位置是相同的

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

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

回答by Praveen

You can try using getVisible()method

您可以尝试使用getVisible()方法

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