【问题标题】:How to add google maps marker from array (javascript)?如何从数组(javascript)添加谷歌地图标记?
【发布时间】:2018-02-03 08:01:47
【问题描述】:

我希望对我的以下 javascript 代码有所支持:

// Initialize Firebase
var config = { 
    apiKey           : "AIzaSyBRC2kza6jhghEFNr5dteVpw2kB9mxqrU8",
    authDomain       : "formulaire-7fba1.firebaseapp.com",
    databaseURL      : "https://formulaire-7fba1.firebaseio.com",
    projectId        : "formulaire-7fba1",
    storageBucket    : "formulaire-7fba1.appspot.com",
    messagingSenderId: "548100244430"
};

firebase.initializeApp(config);

function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: 0, lng: 0},
        zoom: 3,
        styles: [{
            featureType: 'poi',
            stylers: [{ visibility: 'off' }] // Turn off points of interest.
        }, {
            featureType: 'transit.station',
            stylers: [{ visibility: 'off' }] // Turn off bus stations, train stations, etc.
        }],
        disableDoubleClickZoom: true
    });
}

// Loop through users in order with the forEach() method. The callback
// provided to forEach() will be called synchronously with a DataSnapshot
// for each child:
var query = firebase.database().ref("client").orderByKey();
query.once("value").then(function(snapshot) {
    var position = [];

    snapshot.forEach(function(childSnapshot) {
        // key will be "ada" the first time and "alan" the second time
        var key = childSnapshot.key;

        // childData will be the actual contents of the child
        var childData = childSnapshot.val();

        position.push(childData.lat + " " + childData.lng);
        console.log(position);
    });
});

我正在尝试将填充 GPS 位置作为字符串的数组作为标记放入谷歌地图中。尝试了几种方法,但都没有奏效。任何人都可以给我一个提示或方向吗?

谢谢!

【问题讨论】:

    标签: javascript arrays string google-maps


    【解决方案1】:

    如果position 是保存坐标的数组。您需要确保里面的数组元素遵循 latLng 对象或 marker.position 属性将识别的内容。通常它会遵循这种格式:

    var latLngObj = {lat: -25.363, lng: 131.044};

    您可以使用 forEach 循环在每次迭代中添加一个标记。在将坐标推送到 position 数组之前/之后,请执行以下操作:

    var marker = new google.maps.Marker({
              position: {lat: childData.lat, lng:childData.lng},
              map: map
            });
    

    我不确定 childData 的实际外观如何,因为您没有提供该信息,但假设它是 double(如 -25.363)而不是 string,那么它会很好。

    您可能还希望全局定义 map 变量,以便您的函数可以在 map: map 的部分识别它,因为您只是在 initMap 函数中定义 map 变量。

    这里是documentation,可以指导您如何在地图上添加标记。只需使用迭代(例如 for 循环)来添加多个标记。您还将看到如何在同一个 documentation 中删除它们。

    还找到了一个相关的stackoverflow post 正确循环以创建标记。

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-02
      • 1970-01-01
      • 2021-07-22
      • 1970-01-01
      • 2020-10-12
      • 1970-01-01
      相关资源
      最近更新 更多