Google Maps V3拖动标记并更新PolyLine

时间:2013-03-10 16:04:21

标签: javascript google-maps google-maps-api-3

我正在尝试开发一个用户绘制属性的应用程序,它会添加一个标记和一条多边形线,以便他们可以清楚地看到发生了什么。但我想添加拖动标记的功能(这很容易)并更新PolyLine的位置(这不是那么容易吗?)

以下是我的一些代码

这是绘制多边形线的功能

变量' ll' 是google.maps.LatLng的一个实例

// Shorter namespace
    var _g = google.maps;

    // Shorten the namespace, it's used
    // a lot in this function
    var s = SunMaps;

    // If we've reached the max number
    // of lines then exit early.
    if (s.LINES >= 4) {
        return;
    }

    // The defaults
    var options = {
        "strokeColor"   : "green",
        "strokeOpacity" : 1.0,
        "strokeWeight"  : 4
    };

    // If we don't have an instance of poly
    // create one.
    if (s.POLY == false) {
        s.POLY = new _g.Polyline(options);
        s.PATH = s.POLY.getPath();
    }

    // Push the new coords into the path object
    s.PATH.push(ll);

    // Set the map for the poly
    s.POLY.setMap(s.instance);

    // Add a marker
    new s.Marker(ll);

    // Increase the counter
    s.LINES++;  

在同一点绘制标记(行代码中使用的s.Marker函数)

变量' ll' 是google.maps.LatLng的一个实例

var _g = google.maps;

    // Our custom marker
    var marker = new _g.Marker({
        "position" : ll,
        "icon"     : {
            "path" : _g.SymbolPath.CIRCLE,
            "scale": 10
        },
        "draggable": true,
        "map"      : SunMaps.instance,
        "LineIndex": SunMaps.LINES
    });

    _g.event.addListener(marker, 'drag', function (e) {
        console.log(marker.getPosition());
        // Here is where I can't workout or find documentation
        // on how to move the line.
    });

2 个答案:

答案 0 :(得分:2)

path对象的Polyline属性为MVCArray。见https://developers.google.com/maps/documentation/javascript/reference#MVCArray

所以,要移动最后一点你应该能够做到:

s.PATH.setAt(s.PATH.getLength() - 1, marker.getPosition());

答案 1 :(得分:1)

好的,所以我明白了。使用@ Dave的方法

以下是拖动标记

时更新polyLine的代码
    var _g = google.maps;
    var _s = SunMaps;

    // Our custom marker
    var marker = new _g.Marker({
        "position" : ll,
        "icon"     : {
            "path" : _g.SymbolPath.CIRCLE,
            "scale": 7
        },
        "draggable": true,
        "map"      : _s.instance,
        // This is the last known index of a polyLine
        "lineIndex": _s.LINES
    });

    // Listen to the drag event
    _g.event.addListener(marker, 'drag', function (e) {
        // Set the new position of the marker as it drags
        this.setPosition(e.latLng);

        // Update the path
        _s.PATH.setAt(this.lineIndex, this.getPosition());
    });