Reputation: 2796
I'm trying to develop an application where the user draws around a property, it adds a marker and a poly line so they can clearly see what's happening. But I want to add the ability to drag the Marker (this is easy) and update the PolyLine's position (this is not so easy?)
This is the function that draws my poly lines.
the variable 'll' is an instance of 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++;
Draws the markers at the same point (the s.Marker function used in the line code)
the variable 'll' is an instance of 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.
});
Upvotes: 0
Views: 5537
Reputation: 2796
Okay, So I figured it out. Using @Dave's method
Here is the code that updates the polyLine as you drag the marker
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());
});
Upvotes: 1
Reputation: 5178
The path
property of the Polyline
object is an MVCArray
. See https://developers.google.com/maps/documentation/javascript/reference#MVCArray
So, to move the last point you should be able to do:
s.PATH.setAt(s.PATH.getLength() - 1, marker.getPosition());
Upvotes: 2