【问题标题】:How can I use my JSON data to create markers on a google maps API?如何使用我的 JSON 数据在谷歌地图 API 上创建标记?
【发布时间】:2021-06-15 01:12:00
【问题描述】:

我有一堆坐标存储在一个 JSON 对象中,用作一些谷歌地图标记的信息。我正在尝试设置一个“点击”事件监听器,它将使用来自 JSON 对象的数据和 在我的谷歌地图 API 中创建一个标记,但我不知道如何将它们联系在一起。

这是我正在使用的代码。

<select name = "Landmarks and Attractions" id = mySelect onchange="myFunction()">
                <option id="selected" value = "bigBenCoords">Big Ben</option>
                
var myCoordinates = {
            "bigBenCoords" : {"lat":51.5007, "lng":-0.1246}}
            
function myFunction(){
            var x = document.getElementById("mySelect").value;
            console.log(myCoordinates[x]);
            return myCoordinates[x];
        };

function initMap() {

            const map = new google.maps.Map(document.getElementById("map"), {
                zoom: 12,
                center: {
                    lat: 51.509865,
                    lng:  -0.118092
                }
            });
            var markerValue = myFunction();
            console.log("marker value is", markerValue);
            new google.maps.Marker({
                position: myCoordinates["bigBenCoords"],
                map
            });
        }

【问题讨论】:

    标签: javascript json google-maps google-maps-markers event-listener


    【解决方案1】:

    首先,我建议不要使用 onchange 内联属性。这是一项古老的技术,而且不像元素的 addEventListener() 方法那样灵活。

    <select name="Landmarks and Attractions" id="location-select">
      <option value="bigBenCoords">Big Ben</option>
      <option value="statueOfLiberty">Statue Of Liberty</option>
    </select>
    

    您要做的第一件事是选择您的&lt;select&gt; 元素并为您的标记创建一个数组。在添加标记之前,您需要删除所有以前的标记。为此,我们需要存储对标记的引用。
    创建一个名为markers 的数组,我们可以在其中存储创建标记时的标记。

    const locationSelect = document.getElementById('location-select');
    const markers = [];
    
    const myCoordinates = { 
      "bigBenCoords" : {
        "lat": 51.5007, 
        "lng": -0.1246
      },
      "statueOfLiberty": {
        "lat": 40.684155,
        "lng": -74.0594181
      }
    };
    

    现在我们需要创建一个删除所有标记的函数和一个添加单个标记的函数。

    前一个函数将遍历每个标记,并使用每个标记的setMap 方法来断开与地图的连接。循环后它应该清除所有标记的数组。

    后一个函数应采用具有{ lat: number, lng: number} 结构的单个coordinates 对象和map 来添加标记。

    function removeMarkers() {
      markers.forEach(marker => {
        marker.setMap(null); // Disconnect each marker.
      });
    
      markers.length = 0; // This empties the array.
    }
    
    function createMarker(coordinates, map) {
      const marker = new google.maps.Marker({
        position: coordinates,
        map
      });
    
      markers.push(marker); // Add the marker to the array to save the reference.
    }
    

    现在在您的initMap 函数中,创建您的地图,并开始在&lt;select&gt; 元素上监听change 事件。每当值更改时,从选择中获取当前值,根据选定的location 选择您的coordinates,然后调用removeMarkers() 和createMarkers(coordinates, map) 以首先删除所有标记,然后将新标记添加到地图中。

    function initMap() {
      const map = new google.maps.Map(document.getElementById("map"), {
        zoom: 12,
        center: {
          lat: 51.509865,
          lng:  -0.118092
        }
      });
    
      locationSelect.addEventListener('change', () => {
        const location = locationSelect.value;
        const coordinates = myCoordinates[location];
    
        removeMarkers(); // First remove all markers.
        createMarker(coordinates, map); // Then add the marker.
      });
    }
    

    希望这对您有所帮助。如果您有任何问题,请在下方的 cmets 中告诉我。

    【讨论】:

    • 非常感谢!效果很好,我开始扯头发试图弄清楚。我现在要做的就是弄清楚如何在单击各个标记时弹出相应的信息窗口
    • 不客气。如果我正确回答了您的问题,请务必将其标记为已接受。这样其他有相同问题的人就会知道这就是答案,这是一种表示感谢的方式。至于你的下一个问题,关于这个特定问题已经有多个答案(我自己也不得不研究它),所以一定要环顾四周。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2017-08-19
    相关资源
    最近更新 更多