How can I get content out of Google Maps MVCArray? - google-maps

I'm working with google.maps.polygons. The library uses a google.maps.MVCArray element to store the vertices of the polygon where each vertex contains a latitude and longitude variable. So I'm able to create fancy polygons on the fly using user mouse clicks.
var listener1 = google.maps.event.addListener(map, "click", function(e) {
var latLng = e.latLng;
var myMvcArray = new google.maps.MVCArray();
myMvcArray.push(latLng); // First Point
var myPolygon = new google.maps.Polygon({
map: map,
paths: myMvcArray, // one time registration reqd only
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.10,
editable: true,
draggable: false,
clickable: true
});
google.maps.event.removeListener(listener1);
var listener2 = google.maps.event.addListener(map, 'click', function(e) {
latLng = e.latLng;
myMvcArray.push(latLng);
console.log(myMvcArray.getArray());
});
});
My problem is, that console log result is incomprehensible. I've spent a couple of hours trying to figure out how to get clean data from myMvcArray. I need to use the data elsewhere.

So it turns out the trick is this:
console.log(myMvcArray.getArray()[0].lat(), myMvcArray.getArray()[0].lng() );
Which returns: XX.XX2157415679654 -XXX.XX782657623291
A For/Each loop will also work.
myMvcArray.getArray().forEach(function(value, index, array_x) {
console.log(" index: " + index + " value: " + value);
})
Which returns:
index: 0 value: (XX.XX2157415679654, -XXX.XX782657623291)
index: 1 value: (XX.XX209255908967, -XXX.XX77514743805)
Info offered in case anybody else has issues here. Note, too, the code above works pretty well for letting users define a google.maps.polygon on a map easily.

You can use JSON.stringify()
So your code would be
console.log(JSON.stringify(myMvcArray.getArray()))
This works because stringify calls the methods on the MVCArray to get the contents whereas log doesn't.

Related

Incorrect Polyline Click fired when having multiple Polylines on Map

I have multiple polylines on a Google Map and add a 'click' event handler for each. All these polylines are added via javascript code. However when I click on any polyline on map, the click event for the last added polyline is fired. This makes it difficult to identify the line clicked.
The code that creates the Polylines is:
$.ajax({
type: "GET",
url: "MapData.html",
success: function (json) {
mapData = JSON.parse(json);
var newroad;
for (var i = 0; i < mapData.length; i++) {
newroad = new google.maps.Polyline({
ID: mapData[i].ID,
path: google.maps.geometry.encoding.decodePath(mapData[i].latLngs),
strokeColor: 'blue',
strokeOpacity: 0.75,
strokeWeight: 3
});
newroad.setMap(map);
google.maps.event.addListener(newroad, 'click', function () {
setSelectedRoad(newroad);
});
}
},
error: function () {
alert('Critical Data Failure');
}
});
The data is correctly fetched from the server and all polylines are displayed in blue as expected. The function that gets called when a polyline is clicked is
function setSelectedRoad(road) {
road.strokeColor = 'black';
road.setOptions({ strokeColor: 'black', strokeOpacity: 1.0 });
selectedRoadID = road.ID;
}
However the "selectedRoadID" always turns out to be the last polyline added and the color for that line changes to black, even if any other polyline is clicked.
The confusing part is that if I draw a fresh polyline on the map and set its click event to the same function, then that works properly. I do get proper ID for the polyline clicked. This works for any number of new lines drawn and works properly for clicking them in any order.
The problem is you're doing this in a loop:
newroad = new google.maps.Polyline({ ... });
google.maps.event.addListener(newroad, 'click', function () {
setSelectedRoad(newroad);
});
So you re-create newroad let's say 10 times. Each time you create it, you give the same variable a new event listener, i.e. you're overriding the same event listener 10 times. Not creating 10 separate event listeners, one for each polyline.
When you click on your polyline, you're only therefore executing the very last version of the event listener.
Instead you need to separate out the event listener from the loop. Something like this:
$.ajax({
type: "GET",
url: "MapData.html",
success: function (json) {
mapData = JSON.parse(json);
var newroad;
for (var i = 0; i < mapData.length; i++) {
newroad = new google.maps.Polyline({
ID: mapData[i].ID,
path: google.maps.geometry.encoding.decodePath(mapData[i].latLngs),
strokeColor: 'blue',
strokeOpacity: 0.75,
strokeWeight: 3,
map: map
});
bindEvent(newroad);
}
},
error: function () {
alert('Critical Data Failure');
}
});
function bindEvent(newroad) {
newroad.addListener('click', function () {
setSelectedRoad(this);
});
}
This way you call bindEvent 10 times, each time with a different argument for newroad. So you create 10 separate event listeners with a different value for newroad each time.
I found that changing
newroad.setMap(map);
google.maps.event.addListener(newroad, 'click', function () {
setSelectedRoad(newroad);
});
to
newroad.setMap(map);
google.maps.event.addListener(newroad, 'click', function () {
setSelectedRoad(this);
});
fixed everything.

Google Maps Api: Place marker based on % of a line [duplicate]

Here is the code I have so far:
function initialize() {
var mapOptions = {
center: { lat: 21.9072222, lng: -47.715},
zoom: 3
};
var map = new google.maps.Map(document.getElementById('derby-to-lima'),
mapOptions);
var line = new google.maps.Polyline({
path: [new google.maps.LatLng(53.9834124, -1.5863153), new google.maps.LatLng(-12.0553442, -77.0451853)],
strokeColor: "#008CBA",
geodesic: true,
strokeOpacity: 0.5,
strokeWeight: 5,
map: map
});
}
google.maps.event.addDomListener(window, 'load', initialize);
I want to draw another line on top of the existing one that stops at the point in between the two points, which can be changed by percentage. It's kind of hard to explain, but imagine the first point is the start, and the last is the end. You are given how far a runner currently is by the percentage of the way through they are. Now show how far they are (assuming they ran in a straight line).
Thanks, I've been stuck on this for a while.
As suggested by #Dr.Molle load the geometry library and use the method interpolate.
var startPoint = new google.maps.LatLng(53.9834124, -1.5863153);
var endPoint = new google.maps.LatLng(-12.0553442, -77.0451853);
var percentage = 0.5;
var middlePoint = new google.maps.geometry.spherical.interpolate(startPoint, endPoint, percentage);
FIDDLE

how to draw draggable direction using encoded overview polylines

I want to draw drag gable route on Google map using encoded poly line string.So that i can drag route , make changes in it and save in database. can anyone have idea regarding this?????
ex: I have following encoded polyline
var encodedPath='iqgnAa|lxMDq##]j#CrIKhBClEIrFMe#oCCKBa#VqAbAqCEWIi#MSg#[oAu#kAu#aAe#{#WcAScA]g#Mm#EaAV_ECKxBl#BL#FDKpB';
var path = google.maps.geometry.encoding.decodePath( encodedPath );
var polyline = new google.maps.Polyline({
path: path,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 2.0,
strokeWeight: 8
});
polyline.setMap( map );
I want to draw drag gable path on Google map using this encoded poly line path.
Currently i am able to draw poly line on Google map using following code but its is not drag gable
Any suggestions????
also i want draggable behavior like Google map direction service so that i can deviate the existing path and save for future use
You can make it draggable in the constructor
var polyline = new google.maps.Polyline({
path: path,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 2.0,
strokeWeight: 8,
draggable: true
});
or later as
polyline.setDraggable(true);
or
polyline.set('draggable',true);
If you use the polyline to render Google's direction services, the paths will be updated along with the polyline when you drag it. Keep in mind that after doing this you will need to persist the new polyline path to the database. This is done by adding listeners to the polyline path
google.maps.event.addListener(polyline.getPath(), 'set_at', function () {
var encodedpath=google.maps.geometry.encoding.encodePath( polyline.getPath() );
SaveMyPath(encodedpath);
});
google.maps.event.addListener(polyline.getPath(), 'insert_at', function () {
var encodedpath=google.maps.geometry.encoding.encodePath( polyline.getPath() );
SaveMyPath(encodedpath);
});
It's up to you to build the function SaveMyPath

Google Maps v3 href link for polyline

First post so bear with me.
I have a google map that displays polylines.
I create the polylines using the following method:
function createPoly(number,path, color, name) {
var g = google.maps;
var poly = new g.Polyline({
path: path,
strokeColor: color,
strokeOpacity: 1,
strokeWeight: 3
});
var label = new Label({ map: map }, poly);
// Add mouse events to poly
g.event.addListener(poly, "mouseover", function() {
label.add_(name);
poly.setOptions({strokeWeight: 6.0,strokeColor: "#0000FF",});
});
g.event.addListener(poly, "mouseout", function() {
label.remove_();
poly.setOptions({strokeWeight: 3.0,strokeColor: "#FF0000",});
});
g.event.addListener(poly, "click", function() {
$('.LORDesc').empty();
$('.LORDesc').append(name);
});
poly.setMap(map);
return poly;
}
The above code works, and every time I want to create a poly on my map I use:
var MyPoly = createPoly(0,SC001, "#FF0000", "SC001 <BR>Poly 1");
which works fine also.
My problem is I want to create Links to the side of my map and allow the user to hover over the link and have the poly change weight and color. Like it does when the user hovers over the poly on the map. Basically to identify the poly as they hover over the links.
I hope this makes sense.
Any help would be appreciated. I have tried various techniques on my own but have failed.
Regards,
Jonny
You can listen for mouseover and mouseout events on link and trigger event for polyline object. For example:
var linkId = document.getElementById('polylink');
google.maps.event.addDomListener(linkId, 'mouseover', function(event) {
google.maps.event.trigger(polyLine, 'mouseover', {
stop: null,
latLng: new google.maps.LatLng(48, 13.5),
edge: 0,
path: 0,
vertex: 0
});
});
google.maps.event.addDomListener(linkId, 'mouseout', function(event) {
google.maps.event.trigger(polyLine, 'mouseout', {
stop: null,
latLng: new google.maps.LatLng(48, 13.5),
edge: 0,
path: 0,
vertex: 0
});
});
See complete example at jsbin.
If you don't provide the 3rd parameter for trigger method you will get the message error in console:
Uncaught TypeError: Cannot read property 'vertex' of undefined
mouseover and mouseout polyline event handler provides google.maps.PolyMouseEvent object. I made it like it was suggested for google.maps.MouseEvent object in question Simulate a click in a Google Map.
I just add {} to third parameter of trigger function and this error don't show again.
Example: google.maps.event.trigger(yourPolygon, 'mouseover', {});

Create Google Map V3 Polygons from XML data

I am trying to create polygons with Data from a XML file. I have never used polygons before and I have studied the Google Map doc examples to get the base features down but the examples don't even work. I tried to merge it with other things I have learned and used to create markers and poly lines but I am missing something and now not only do the polygons not show but the map doesn't even show. I start with base code to display the map and start from there. Once I started adding the code to build the polygon it causes the map to not load. I know I am missing something but I am not sure what exactly since I have never used polygons before.
You can view an example of the XML file I am using for the data. The cords to create the polygons are in a element called "cap:polygon".
http://www.mesquiteweather.net/xml/warnings.xml
Here is the code I have so far...
<script type="text/javascript">
var lineColor = {
"Tornado Warning": "#FF0000",
"Severe Thunderstorm Warning": "#FFFF33",
"Flash Flood Warning": "#00FF00",
};
var infowindow = new google.maps.InfoWindow();
// start here
var thisurl = 'xml/warnings.xml';
function initialize() {
var myLatlng = new google.maps.LatLng(32.775833, -96.796667);
var myOptions = {
panControl: false,
zoom: 5,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL,
position: google.maps.ControlPosition.RIGHT_TOP
},
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
function MyLogoControl(controlDiv) {
controlDiv.style.padding = '5px';
var logo = document.createElement('IMG');
logo.src = 'http://www.mesquiteweather.net/images/watermark_MW_GMap.png';
logo.style.cursor = 'pointer';
controlDiv.appendChild(logo);
google.maps.event.addDomListener(logo, 'click', function() {
window.location = 'http://www.mesquiteweather.net';
});
}
var logoControlDiv = document.createElement('DIV');
var logoControl = MyLogoControl(logoControlDiv);
logoControlDiv.index = 0; // used for ordering
map.controls[google.maps.ControlPosition.TOP_LEFT].push(logoControlDiv);
var eventWarnings;
downloadUrl(thisurl, function(data) {
var polygon = data.documentElement.getElementsByTagName("feed");
var warningCoords = new google.maps.LatLng(cap:polygon),
});
// Construct the polygon
eventWarnings = new google.maps.Polygon({
paths: warningCoords,
strokeColor: lineColor[cap:event],
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: lineColor[cap:event],
fillOpacity: 0.35
});
eventWarnings.setMap(map);
}
</script>
I am stuck at this point and not sure what I am missing. If anyone can offer some advice or suggestions that would be great!
-Thanks!
This is incorrect (I would expect it to give you a javascript error):
var warningCoords = new google.maps.LatLng(cap:polygon)
A google.maps.LatLng takes two numbers as an argument. You need to parse the coordinates out of the XML feed, convert them into google.maps.LatLng objects, push them into an array, then provide that array as the paths property in the google.maps.Polygon constructor.