【问题标题】:google.maps.Polyline (JavaScript API) "path" property does not get initializedgoogle.maps.Polyline(JavaScript API)“路径”属性未初始化
【发布时间】:2017-12-05 11:43:26
【问题描述】:

我从 Google Maps 的 JavaScript API 中的 google.maps.Polyline 类收到某种奇怪的行为。

我想要实现的目标很简单 - 从不断更新的 LatLngLiteral 数组在地图上绘制折线。

问题 - google.maps.Polyline 的“路径”属性未初始化,因此折线不可见。奇怪的是,不管我在 google.maps.Polyline 的初始化中包含“路径”属性,加载地图后,这样的属性不存在(尽管创建了 Polyline 对象并且我可以访问它的其他属性)。

我得到的确切错误:“Cannot read property 'push' of undefined at ok (map.js:74)”。我尝试通过 setPath() 方法设置“路径”的值,我尝试使用 LatLng 类,尝试 MVCArray 类 - 没有任何效果。提前感谢你的帮助!代码如下。 (下面的代码没有优化,我只是从这个项目的基本功能开始)

function loadMap(){
    var options = {
        zoom : 15,
        center : {lat:42.553080288955805, lng: 11.25}                               
    };
    map = new google.maps.Map(document.getElementById("test-map"),options);
    player  = new google.maps.Marker(
            {
                map: map,
                position: {lat:42.553080288955805, lng: 11.25},
                title: "This is you!",
                label: {
                    text: "You are here!",
                    color: "rgb(50,50,255)",
                    fontFamily: "Helvetica, sans-serif",
                    fontWeight: "bold"
                }
            });

    //initializing path variable
    pathArray = [
        new google.maps.LatLng(-42, 11), 
        new google.maps.LatLng(-43, 12), 
        new google.maps.LatLng(-44, 15)
    ];
    playerPath = new google.maps.Polyline({
        map: map,
        path: pathArray, //the value here is not assigned for some reason
        strokeColor: "orange", //this property and value is assigned and 
                               //accessible after the map was loaded
        visible: true
    });

}

let options2 = {
        enableHighAccuracy : true,
        timeout : 10000,
        maximumAge : 30000
    };


var positionWatcher = navigator.geolocation.watchPosition(ok,null,options2);
function ok(p){
    player.setPosition({lat:p.coords.latitude, lng:p.coords.longitude}); // works ok
    playerPath.path.push({lat:p.coords.latitude, lng:p.coords.longitude});
//above line provides the mentioned error
}

【问题讨论】:

  • 好的,没问题,如果现在可读性更好,请看一下。

标签: javascript api maps


【解决方案1】:

由于对此没有回复,我深入挖掘并找到了一个可行的解决方案,但是为什么在 Polyline 实例创建期间没有创建此对象的 "path" 属性的问题仍然让我感到困惑。

无论如何,"path" 属性似乎在初始化期间仅接受 google.maps.MVCArray([LatLng, LatLng]) 作为值。 JavaScript API 说它应该接受带有 LatLng 或 LatLngLiteral 作为元素的常规 Array 对象,但事实并非如此(至少在我的代码中,这很简单)。

所以如果你有同样的问题,我建议像这样初始化路径:

pathArray = new google.maps.MVCArray([
        new google.maps.LatLng(-42, 11), 
        new google.maps.LatLng(-43, 12), 
        new google.maps.LatLng(-44, 15)
    ]);

    playerPath = new google.maps.Polyline({
        map: map,
        path: pathArray
    }); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 2019-12-02
    • 2021-06-21
    • 2017-03-03
    • 2012-05-26
    • 1970-01-01
    相关资源
    最近更新 更多