首页 > 解决方案 > Vuejs谷歌地图在中心圈内显示标记/坐标

问题描述

如何显示在我的中心半径内的标记?我需要根据半径显示地点,因为这将是我根据地点的公里半径创建功能来查找此类地点的基础。

这是我的地图 在此处输入图像描述

如您所见,我有很多标记。通过调用 axios 请求来自我的数据库。

这是我的代码片段

     data() {
         return {
            clinics: [],
            points: '',
            property: {
               lat: 1.28237,
               lng: 103.783098
            },
            diameter: 5000
         }
      },
      methods: {
         initMap() {
            //center marker from circle
            const map = new google.maps.Map(document.getElementById('map'), {
               zoom: 13,
               center: this.property
            })
            const circle = new google.maps.Circle({
               map: map,
               trokeColor: '#FF0000',
               strokeOpacity: 0.8,
               strokeWeight: 2,
               fillColor: '#FF0000',
               fillOpacity: 0.35,
               radius: this.diameter,
               center: this.property
            });
            const marker = new google.maps.Marker({
               position: this.property,
               map: map
            });

            //other Markers
            for (var i = 0; i < this.clinics.data.length; i++) {
               var coords = this.clinics.data[i].coord;
               var details = this.clinics.data[i].clinic;
               var latLng = new google.maps.LatLng(coords['lat'], coords['lng']);
               var markers = new google.maps.Marker({
                  position: latLng,
                  map: map,
               });
               const contentString = '<div id="content"><p>' + details + '</p></div>';
               //for Info window function
               this.infoWindowShow(markers, contentString);
            }
         }

标签: javascriptgoogle-mapsvue.jsgoogle-maps-api-3

解决方案


您可以在 for 循环中放置一个函数,该函数将检查圆心与标记坐标之间的距离是否小于或等于您在绘制之前设置的半径。它应该看起来像这样。

    for (var i = 0; i < this.clinics.data.length; i++) {
               var coords = this.clinics.data[i].coord;
               var details = this.clinics.data[i].clinic;
               var latLng = new google.maps.LatLng(coords['lat'], coords['lng']);

        //Get distance between the center of the circle and the coordinates
    var dist  = google.maps.geometry.spherical.computeDistanceBetween(CenterOfCircle,latLng);    

    //If distance is less than the radius, plot the markers in the map
    if (dist <= radiusOfCircle){
               var markers = new google.maps.Marker({
                  position: latLng,
                  map: map,
               });
               const contentString = '<div id="content"><p>' + details + '</p></div>';
               //for Info window function
               this.infoWindowShow(markers, contentString);
            }
  }

您可以使用几何库的 computeDistanceBetween()。确保在调用 Google Maps API 的脚本中添加“libraries=geometry”。

这是一个简单的代码,它只是在一组坐标中循环,这里是对简单代码的修改,它只在圆圈内绘制标记

希望这适用于您的实施!


推荐阅读