Google map polyline double click event - google-maps

I have some sample polylines here where I am trying to fire double click event on each polylines.
I tried with,
google.maps.event.addListener(poly, 'dblclick', (function (poly, i) {
alert();
})(poly, i));
Butit gives the alert on loading the map only. So how can I fire double click event on polylines?

Two issues:
There is no function for your dblclick listener as written, the alert is run immediately and its return value is used as the click listener function.
Once the infowindow opens on the click listener, it blocks the polyline so it doesn't get the second click
If I move the infowindow so it doesn't block the second click and fix the dblclick event listener function, it works.
proof of concept fiddle
code snippet:
(note that alert doesn't work in the code snippet, produces this error: Ignored call to 'alert()'. The document is sandboxed, and the 'allow-modals' keyword is not set.)
var map;
var infowindow = new google.maps.InfoWindow();
function initialize() {
var mapOptions = {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var bounds = new google.maps.LatLngBounds();
var polygons = [];
var arr = new Array();
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
for (var i in coordinates) {
arr = [];
for (var j = 0; j < coordinates[i].length; j++) {
arr.push(new google.maps.LatLng(
parseFloat(coordinates[i][j][0]),
parseFloat(coordinates[i][j][1])));
bounds.extend(arr[arr.length - 1])
}
var lineSymbol = {
path: 'M 0,-1 0,1',
strokeOpacity: 1,
// strokeWeight: 1,
scale: 4
};
var strOp = 1;
var icons = [];
if (i == "feed5") {
icons = [{
icon: lineSymbol,
offset: '0',
repeat: '20px'
}];
strOp = 0;
}
// Construct the polygon.
polygons.push(new google.maps.Polyline({
path: arr,
strokeColor: '#FF0000',
strokeOpacity: strOp,
strokeWeight: 2,
icons: icons,
}));
var poly = polygons[polygons.length - 1];
poly.setMap(map);
google.maps.event.addListener(poly, 'dblclick', (function(poly, i) {
return function() {
alert();
}
})(poly, i));
google.maps.event.addListener(poly, 'click', (function(poly, i) {
return function(event) {
infowindow.setContent("" + i);
infowindow.setPosition(google.maps.geometry.spherical.computeOffset(event.latLng, 90, 10000));
infowindow.open(map);
};
})(poly, i));
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
// Define the LatLng coordinates for the polygon's path.
var coordinates = {
"feed1": [
[12.991838, 77.70851],
[12.9912195, 77.707405],
[12.989732, 77.705246],
[12.989732, 77.70416]
],
"feed2": [
[12.999084, 77.71209],
[13.004616, 77.71334]
],
"feed3": [
[12.993468, 77.711845],
[12.992951, 77.71133],
[12.992114, 77.71015],
[12.99217, 77.708626],
[12.991289, 77.70722],
[12.989901, 77.70519],
[12.989763, 77.70434]
],
"feed4": [
[13.298387, 77.55231],
[13.297882, 77.552536],
[13.295542, 77.55311],
[13.293249, 77.55186],
[13.29154, 77.551544],
[13.290586, 77.55115],
[13.290111, 77.54973],
[13.288905, 77.54885],
[13.286778, 77.54691],
[13.28569, 77.54599],
[13.283473, 77.54516],
[13.28245, 77.54316],
[13.279767, 77.54178],
[13.278179, 77.541046],
[13.276475, 77.540146],
[13.276237, 77.53926]
],
"feed5": [
[13.295467, 77.55559],
[13.296861, 77.55374],
[13.298651, 77.55295]
]
};
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="map-canvas"></div>

Remove click listener and try like this:
google.maps.event.addListener(poly, 'dblclick', function() {
alert("test");
});
Listener won't work both click and dblclick

Related

Fire event after polygon is loaded

After searching the whole day, I didn't find the answer.
So the problem is:
I have a Google Map on which the user can draw. After this, the user can save it on the server. It works fine. Here is the drawing code:
var drawingManager;
var selectedShape;
var colors = ['#1E90FF', '#FF1493', '#32CD32', '#FF8C00', '#4B0082'];
var selectedColor;
var colorButtons = {};
var all_overlays = [];
var coordinates;
var polygon;
var globalGoogleSelectedColor;
var globalGooglePinWidth;
var map;
coordObj = new Object();
function clearSelection()
{
if (selectedShape)
{
deleteAllLastShape();
selectedShape.setEditable(false);
selectedShape = null;
deleteObjectContent(coordObj);
}
}
function setSelection(shape)
{
clearSelection();
selectedShape = shape;
shape.setEditable(true);
selectColor(shape.get('fillColor') || shape.get('strokeColor'));
}
function deleteAllShape()
{
console.log("deleteAllShape");
deleteObjectContent(coordObj);
for (var i=0; i < all_overlays.length; i++)
{
all_overlays[i].overlay.setMap(null);
}
all_overlays = [];
}
function deleteAllLastShape()
{
var myLenth = all_overlays.length;
if(myLenth > 1)
{
all_overlays[0].overlay.setMap(null);
all_overlays = _.rest(all_overlays);
}
}
function deleteSelectedShape()
{
if (selectedShape)
{
selectedShape.setMap(null);
deleteObjectContent(coordObj);
}
}
function selectColor(color)
{
selectedColor = color;
globalGoogleSelectedColor = selectedColor;
globalGooglePinWidth = 2; //only for Database
for (var i = 0; i < colors.length; ++i)
{
var currColor = colors[i];
colorButtons[currColor].style.border = currColor == color ? '2px solid #789' : '2px solid #fff';
}
// Retrieves the current options from the drawing manager and replaces the
// stroke or fill color as appropriate.
var polylineOptions = drawingManager.get('polylineOptions');
polylineOptions.strokeColor = color;
drawingManager.set('polylineOptions', polylineOptions);
var rectangleOptions = drawingManager.get('rectangleOptions');
rectangleOptions.fillColor = color;
drawingManager.set('rectangleOptions', rectangleOptions);
var circleOptions = drawingManager.get('circleOptions');
circleOptions.fillColor = color;
drawingManager.set('circleOptions', circleOptions);
var polygonOptions = drawingManager.get('polygonOptions');
polygonOptions.fillColor = color;
drawingManager.set('polygonOptions', polygonOptions);
}
function setSelectedShapeColor(color)
{
if (selectedShape)
{
if (selectedShape.type == google.maps.drawing.OverlayType.POLYLINE)
{
selectedShape.set('strokeColor', color);
}
else
{
selectedShape.set('fillColor', color);
}
}
}
function makeColorButton(color)
{
var button = document.createElement('span');
button.className = 'color-button';
button.style.backgroundColor = color;
google.maps.event.addDomListener(button, 'click', function() {
selectColor(color);
setSelectedShapeColor(color);
});
return button;
}
function buildColorPalette()
{
var colorPalette = document.getElementById('color-palette');
for (var i = 0; i < colors.length; ++i)
{
var currColor = colors[i];
var colorButton = makeColorButton(currColor);
colorPalette.appendChild(colorButton);
colorButtons[currColor] = colorButton;
}
selectColor(colors[0]);
}
function initializeAreas()
{
map = new google.maps.Map(document.getElementById('mapBaugebieteDiv'),
{
zoom: 15,
center: new google.maps.LatLng(48.758961357888516,8.240861892700195),
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DEFAULT,
mapTypeIds: [
google.maps.MapTypeId.ROADMAP,
google.maps.MapTypeId.TERRAIN,
google.maps.MapTypeId.SATELLITE,
google.maps.MapTypeId.HYBRID
]},
disableDefaultUI: false,
zoomControl: true,
scaleControl: true,
mapTypeControl: true,
streetViewControl: true,
rotateControl: true
});
var polyOptions =
{
strokeWeight: 0,
fillOpacity: 0.45,
editable: true
};
// Creates a drawing manager attached to the map that allows the user to draw
// markers, lines, and shapes.
drawingManager = new google.maps.drawing.DrawingManager(
{
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
// google.maps.drawing.OverlayType.MARKER,
// google.maps.drawing.OverlayType.CIRCLE,
google.maps.drawing.OverlayType.POLYLINE,
// google.maps.drawing.OverlayType.RECTANGLE,
google.maps.drawing.OverlayType.POLYGON
]
},
markerOptions:
{
draggable: true
},
polylineOptions:
{
editable: true
},
rectangleOptions: polyOptions,
circleOptions: polyOptions,
polygonOptions: polyOptions,
map: map
});
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e)
{
// Push the overlay onto an array (all_overlays):
all_overlays.push(e);
deleteAllLastShape();
if (e.type != google.maps.drawing.OverlayType.MARKER)
{
// Switch back to non-drawing mode after drawing a shape.
drawingManager.setDrawingMode(null);
// Add an event listener that selects the newly-drawn shape when the user
// mouses down on it.
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, 'click', function()
{
setSelection(newShape);
});
setSelection(newShape);
}
});
// Clear the current selection when the drawing mode is changed, or when the
// map is clicked.
google.maps.event.addListener(drawingManager, 'drawingmode_changed', clearSelection);
google.maps.event.addListener(map, 'click', clearSelection);
google.maps.event.addDomListener(document.getElementById('delete-button'), 'click', deleteSelectedShape);
google.maps.event.addDomListener(document.getElementById('delete-all-button'), 'click', deleteAllShape);
///////////////////////////////////////
// Polylgon
///////////////////////////////////////
google.maps.event.addListener(drawingManager, 'polygoncomplete', function (polygon)
{
var shapeType = 'polygon';
google.maps.event.addListener(polygon.getPath(), 'insert_at', function()
{
// New point
coordinates = (polygon.getPath().getArray());
showObjectContent(coordinates);
coordObj = getCoordinatesOfPolygon(polygon,shapeType);
});
google.maps.event.addListener(polygon.getPath(), 'remove_at', function()
{
// Point was removed
coordinates = (polygon.getPath().getArray());
coordObj = getCoordinatesOfPolygon(polygon,shapeType);
});
google.maps.event.addListener(polygon.getPath(), 'set_at', function()
{
// Point was moved
coordinates = (polygon.getPath().getArray());
coordObj = getCoordinatesOfPolygon(polygon,shapeType);
});
google.maps.event.addListener(polygon, 'dragend', function()
{
// Polygon was dragged
coordinates = (polygon.getPath().getArray());
coordObj = getCoordinatesOfPolygon(polygon,shapeType);
});
coordinates = (polygon.getPath().getArray());
coordObj = getCoordinatesOfPolygon(polygon,shapeType);
});
///////////////////////////////////////
// Polyline
///////////////////////////////////////
google.maps.event.addListener(drawingManager, 'polylinecomplete', function (polygon)
{
var shapeType = 'polyline';
google.maps.event.addListener(polygon.getPath(), 'insert_at', function()
{
// New point
coordinates = (polygon.getPath().getArray());
coordObj = getCoordinatesOfPolygon(polygon,shapeType);
});
google.maps.event.addListener(polygon.getPath(), 'remove_at', function()
{
// Point was removed
coordinates = (polygon.getPath().getArray());
coordObj = getCoordinatesOfPolygon(polygon,shapeType);
});
google.maps.event.addListener(polygon.getPath(), 'set_at', function()
{
// Point was moved
coordinates = (polygon.getPath().getArray());
coordObj = getCoordinatesOfPolygon(polygon,shapeType);
});
google.maps.event.addListener(polygon, 'dragend', function()
{
// Polygon was dragged
coordinates = (polygon.getPath().getArray());
coordObj = getCoordinatesOfPolygon(polygon,shapeType);
});
coordinates = (polygon.getPath().getArray());
coordObj = getCoordinatesOfPolygon(polygon,shapeType);
});
buildColorPalette();
}
google.maps.event.addDomListener(window, 'load', initializeAreas);
But the big problem is, after reloading the lat/lng from the server and drawing it on the map, the event listener does not know about the new polygon:
function fillBuildingForm(getData)
{
var coord = getData['buildings']; // coordinates from the server
if(typeof coord[0] !== 'undefined')
{
var shapeType = coord[0]['shapeType'];
var color = coord[0]['color'];
var strokeOpacity = coord[0]['opacity'];
var strokeWeight = coord[0]['linewidth'];
var numberOfCoord = getObjectSize(coord);
var flightPlanCoordinates = new Array();
for (var i = 0; i < numberOfCoord; i++)
{
thisCoord = new Object();
thisCoord['lat']=parseFloat(coord[i]['lat']);
thisCoord['lng']=parseFloat(coord[i]['lng']);
flightPlanCoordinates.push(thisCoord);
};
var bermudaTriangle = new google.maps.Polygon(
{
paths: flightPlanCoordinates,
strokeColor: color,
strokeOpacity: strokeOpacity,
strokeWeight: strokeWeight,
fillColor: color,
fillOpacity: 0.35,
// bounds: flightPlanCoordinates,
editable: true,
draggable: true
});
bermudaTriangle.setMap(map); //now its drawing at the map
}
}
You can see, until now, it works perfectly:
But the user can change the polygon and want to save the new changed polygon on the server. The listener:
google.maps.event.addListener(drawingManager, 'polygoncomplete', function (polygon)
Does not recognize that the polygon has been drawn. And therefore the listener doesn't recognize when the user changes the polygon.
So the coordinates are not present in all_overlays[i].
The listener only recognizes when a polygon is drawn manually, but not in the way like the above, when it is drawn automatically.
The question: How can I send the automatically drawn polygon coordinates to the "map" object? Alternatively, how can I fire an event to "polygoncomplete", so it will recognize the new polygon?
The other idea I had: Trigger a mouse click event at the map with the coordinates, so the listener must recognize that the map has changed. But unfortunately this didn't work.
Has anybody any idea how to solve this issue?
There are not many possibilities as an event "polygon_load _complete" is not available. One suggestion is to exploit the fact that to operate on a polygon you must click it.
If you need to manage the situation when a polygon is loaded from server and the user change the shape/coordinates. you can add listener on click to every polygon during the loading phase ..
for each polygon in loading phase..
var aPoly = new google.maps.Polygon({
paths:myPaths,
.......
});
google.maps.event.addListener(aPoly, 'click', function (event) {
console.log('This polygon contain : ' + this.paths + ' coords point ');
});
In this way you can intecept the click on polygon for manage your need
your idea was a good intention, but not the end of the solution. But thank you for your hint. Because of your answer I was able finding a way.
Generally we should think, the object bermudaTriangle should have the property "paths". But it doesn't work like this way.
For getting the coordinates of the loaded Poly (loaded from server) there is a google-map function like "getPath()" or"getPaths()". It seems, that both methods are working.
Please note, I've changed the name from 'bermudaTriangle' to 'globalLoadedPoly'.
So the solution is in combination with the above code now additional:
Creating a global var:
var globalLoadedPoly;
(global is not necessary, but I did it this way for further actions)
Getting the path by function for the listeners:
var thisPolyPath = globalLoadedPoly.getPath();
Listening to events, when the loaded poly has changed:
google.maps.event.addListener(thisPolyPath, 'set_at', thisPolyHasChanged);
google.maps.event.addListener(thisPolyPath, 'insert_at', thisPolyHasChanged);
4.In the function, thisPolyHasChanged(), setting the loaded poly as the actual selection, by using the function setSelection(shape). And getting the coordinates by calling the function getCoordinatesOfLoadedPolygon
function thisPolyHasChanged()
{
// Setting the loaded poly as the new selection
// Yes, it's global, so therefore not necessary to be sent
// but like this way, it's more readable
setSelection(globalLoadedPoly);
// If you want to get the coordinates for saving
// Calling the function getCoordinatesOfLoadedPolygon
// For being more readable I send the global Object - yes, it's not necessary
coordObj = getCoordinatesOfLoadedPolygon(globalLoadedPoly,'polygon');
// do something with coordObj
// ...
}
function setSelection(shape)
{
// clearSelection is in the code I postet as the question
clearSelection();
selectedShape = shape; // setting the loaded poly as the actual poly
shape.setEditable(true); // making the loaded poly editable
selectColor(shape.get('fillColor') || shape.get('strokeColor')); //setting the color
}
function getCoordinatesOfLoadedPolygon(getPolygon,shapeType)
{
// getLength is also a google-maps function / method
var objSize = getPolygon.getPath().getLength();
for (var i = 0; i < objSize; i++)
{
// getArray is a google-maps function / method too
var thisLat = getPolygon.getPath().getArray()[i].lat();
var thisLng = getPolygon.getPath().getArray()[i].lng();
coordObj[i]=new Object();
coordObj[i]['lat']=thisLat;
coordObj[i]['lng']=thisLng;
coordObj[i]['shapeType']=shapeType;
};
return coordObj;
}
At last, if you iterate the object "coordObj" and make a console.log in firebug, it looks like this way:
0 Object { lat=51.25572693191116, lng=9.136230200529099, shapeType="polygon"}
1 Object { lat=51.80250070611026, lng=13.069335669279099, shapeType="polygon"}
2 Object { lat=49.958995050387585, lng=10.476562231779099, shapeType="polygon"}
Conclusion:
If you want to get the coordinates or other properties of a google-maps object, use the proprietary google-maps functions / methods:
// For getting the coordinates you are generally working with:
yourMapObject.getPath();
//or
yourMapObject.getPaths();
// Getting especially the latitude:
var latitude = yourMapObject.getPath().getArray()[i].lat();
// Getting especially the longitude:
var longitude = yourMapObject.getPath().getArray()[i].lng();
// Getting the number of coordinates
yourMapObject.getPath().getLength();
Don't forget to iterate over the whole object, to get all coordinates.
The solution-code could be really optimized. For being more readable, I wrote it in small steps.
I hope, I'm able helping anybody with this solution.

Draw route on Google Maps taking coordinates from a database

Below is a map to demonstrate the type of output I would like to achieve.
However, when I fetch the coordinates from the database I don't know how to draw them on Google Maps in order to get this type of output. I use this code but I don't how to put coordinates in this code from the database.
var MapPoints = '[{"address":{"address":"plac Grzybowski, Warszawa, Polska","lat":"52.2360592","lng":"21.002903599999968"},"title":"Warszawa"},{"address":{"address":"Jana Paw\u0142a II, Warszawa, Polska","lat":"52.2179967","lng":"21.222655600000053"},"title":"Wroc\u0142aw"},{"address":{"address":"Wawelska, Warszawa, Polska","lat":"52.2166692","lng":"20.993677599999955"},"title":"O\u015bwi\u0119cim"}]';
var MY_MAPTYPE_ID = 'custom_style';
function initialize() {
if (jQuery('#map').length > 0) {
var locations = jQuery.parseJSON(MapPoints);
window.map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
});
var infowindow = new google.maps.InfoWindow();
var flightPlanCoordinates = [];
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].address.lat, locations[i].address.lng),
map: map
});
flightPlanCoordinates.push(marker.getPosition());
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i]['title']);
infowindow.open(map, marker);
}
})(marker, i));
}
map.fitBounds(bounds);
var flightPath = new google.maps.Polyline({
map: map,
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
You're adding markers to the map so you can extract their coordinates to make a polyline. You can cut out the middleman and use the LatLngs to make the polyline.
$('document').ready(function() {
initialize();
});
// You don't need google.maps.event.addDomListener(window, 'load', initialize);
// if you use jQuery's $(document).ready() function.
function initialize() {
var flightPathCoordinates = [];
// Get the data from the server.
$.get(
"url/of/serverScript.php", // Wherever you're getting your var MapPoints JSON.
function(response) {
var locations = $.parseJSON(response);
var coordinatePair;
for (i = 0; i < locations.length; i++) {
coordinatePair = new google.maps.LatLng(locations[i].address.lat,
locations[i].address.lng);
flightPathCoordinates.push(coordinatePair);
}
}); // end $.get()
// Create the map.
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
});
// Create the polyline.
var flightPath = new google.maps.Polyline({
map: map,
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
// Add it to the map.
flightPath.setMap(map);
}
Note: You can use $ instead of jQuery. e.g. these are equivalent: jQuery('#map') $('#map')

Google maps v3 decode polygon(s) from MySQL database

I would like to draw one or more polygons which are saved encoded in the MySQL database. I've based my code on the known bermudatriangle script example. The XML from "polygon_xml.php" is OK. For now, there's only 1 encoded coordinate in the database. At: //alert1(decodedPolygon); the coordinates are shown, but at //alert2(decodedPolygon); it's not. It has something to do with the array decodedPolygon I guess. What makes me more confusing is that the polygon does show when I uncomment //alert2(decodedPolygon);. Alert2 is empty but after clicking "OK", the polygon is shown on the map!??? Finally I would like to add text to the XML and place it in the infowindow instead of the coordinates.
My 3 encoded coordinates are:
{zzfIsjmu#kHuczRrg{NxcsO}t{GtczR
a}~cIqcskBu|sEov{OoxNel}AfccMwfzG~q|#nknX}u~GvczR
cljkHmfoQl|J{hrV~syGzhrV
I hope somebody can help / explain.
Here's my code so far:
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry">
<script>
var map;
var infoWindow;
var decodedPolygon = [];
function initialize() {
var mapOptions = {
zoom: 3,
center: new google.maps.LatLng(49.724479, 17.578125),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
downloadUrl("polygon_xml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
//var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
var encodedPath = markers[i].getAttribute("coords");
decodedPolygon = google.maps.geometry.encoding.decodePath(encodedPath);
//alert1(decodedPolygon);
//bounds.extend(decodedPolygon);
}
})
//alert2(decodedPolygon);
// Construct the polygon.
bermudaTriangle = new google.maps.Polygon({
paths: decodedPolygon,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FF0000',
fillOpacity: 0.35
});
bermudaTriangle.setMap(map);
// Add a listener for the click event.
google.maps.event.addListener(bermudaTriangle, 'click', showArrays);
infoWindow = new google.maps.InfoWindow();
}
/** #this {google.maps.Polygon} */
function showArrays(event) {
// Since this polygon has only one path, we can call getPath()
// to return the MVCArray of LatLngs.
var vertices = this.getPath();
var contentString = '<b>Bermuda Triangle polygon</b><br>' +
'Clicked location: <br>' + event.latLng.lat() + ',' + event.latLng.lng() +
'<br>';
// Iterate over the vertices.
for (var i = 0; i < vertices.getLength(); i++) {
var xy = vertices.getAt(i);
contentString += '<br>' + 'Coordinate ' + i + ':<br>' + xy.lat() + ',' +
xy.lng();
}
// Replace the info window's content and position.
infoWindow.setContent(contentString);
infoWindow.setPosition(event.latLng);
infoWindow.open(map);
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<body>
<div id="map-canvas"></div>
downloadUrl is asynchronous, you need to use the data returned inside the callback routine. Right now, the bermudaTriangle polygon is constructed before the data is returned (outside of the callback function).
function initialize() {
var mapOptions = {
zoom: 3,
center: new google.maps.LatLng(49.724479, 17.578125),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
downloadUrl("polygon_xml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
var encodedPath = markers[i].getAttribute("coords");
var decodedPolygon = google.maps.geometry.encoding.decodePath(encodedPath);
for (var j = 0; j < decodedPolygon.length; j++) {
bounds.extend(decodedPolygon[j]);
}
// Construct the polygon.
var bermudaTriangle = new google.maps.Polygon({
paths: decodedPolygon,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FF0000',
fillOpacity: 0.35
});
bermudaTriangle.setMap(map);
// Add a listener for the click event.
google.maps.event.addListener(bermudaTriangle, 'click', showArrays);
}
map.fitBounds(bounds);
})
infoWindow = new google.maps.InfoWindow();
}
proof of concept fiddle

Get the lat lng when plotting the polygon points

I am trying to get the lat lng of the polygon while drawing the polygon on google map. Does anyone know what event is triggered when we plot the points of polygon.
Basically what I am trying to do is undo/redo function for the polygon. So when a user plots 2 points one then clicks undo then it should be able to delete 1 point on one click.
As the map click event is disabled while drawing a polygon how to get the lat lng points? Is it possible what I am trying to do? Can anyone please help me with this? Any links or examples that I could refer to?
Below is my code to draw polygon:
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: false,
polygonOptions: {
strokeWeight: 2,
fillOpacity: 0.2,
editable: true,
fillColor: '#FFF000',
strokeColor: '#FFF000',
geodesic: true,
suppressUndo: true
},
polylineOptions: {
editable: false,
suppressUndo: true
}
});
drawingManager.setMap(map);
Try this
var myPoly;
google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {
myPoly = polygon;
get_coordinates(polygon);//call to get coordinates
//editing polygon function
google.maps.event.addListener(polygon.getPath(), 'set_at', function() {
get_coordinates(polygon);//call to get coordinates
});
var newShape = polygon.overlay;
//newShape.type = polygon.type;
google.maps.event.addListener(newShape, 'click', function() {
setSelection(newShape);
});
setSelection(newShape);
});
and the get coordinate function
//function to get coordinates of polygon
function get_coordinates(polygon){
var full_path = [];//initialize array for set coordinates.
polygon.getPath().forEach(function(elem, index){
full_path.push(elem.toUrlValue());
});
return full_path;
}
ok. I can give you all the functions you need. You can integrate last code with the following. And you cannot delete any point but replace it.
var drawingManager;
var selectedShape;
var colors = ['#1E90FF', '#FF1493', '#32CD32', '#FF8C00', '#4B0082'];
var selectedColor;
var colorButtons = {};
function clearSelection() {
if (selectedShape) {
selectedShape.setEditable(false);
selectedShape = null;
}
}
function setSelection(shape) {
clearSelection();
selectedShape = shape;
shape.setEditable(true);
selectColor(shape.get('fillColor') || shape.get('strokeColor'));
}
function deleteSelectedShape() {
if (selectedShape) {
selectedShape.setMap(null);
}
}
function selectColor(color) {
selectedColor = color;
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
colorButtons[currColor].style.border = currColor == color ? '2px solid #789' : '2px solid #fff';
}
// Retrieves the current options from the drawing manager and replaces the
// stroke or fill color as appropriate.
var polylineOptions = drawingManager.get('polylineOptions');
polylineOptions.strokeColor = color;
drawingManager.set('polylineOptions', polylineOptions);
var rectangleOptions = drawingManager.get('rectangleOptions');
rectangleOptions.fillColor = color;
drawingManager.set('rectangleOptions', rectangleOptions);
var circleOptions = drawingManager.get('circleOptions');
circleOptions.fillColor = color;
drawingManager.set('circleOptions', circleOptions);
var polygonOptions = drawingManager.get('polygonOptions');
polygonOptions.fillColor = color;
drawingManager.set('polygonOptions', polygonOptions);
}
function setSelectedShapeColor(color) {
if (selectedShape) {
if (selectedShape.type == google.maps.drawing.OverlayType.POLYLINE) {
selectedShape.set('strokeColor', color);
} else {
selectedShape.set('fillColor', color);
}
}
}
function makeColorButton(color) {
var button = document.createElement('span');
button.className = 'color-button';
button.style.backgroundColor = color;
google.maps.event.addDomListener(button, 'click', function() {
selectColor(color);
setSelectedShapeColor(color);
});
return button;
}
function buildColorPalette() {
var colorPalette = document.getElementById('color-palette');
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
var colorButton = makeColorButton(currColor);
colorPalette.appendChild(colorButton);
colorButtons[currColor] = colorButton;
}
selectColor(colors[0]);
}
function initialize() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(22.344, 114.048),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
zoomControl: true
});
var polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true
};
// Creates a drawing manager attached to the map that allows the user to draw
// markers, lines, and shapes.
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
markerOptions: {
draggable: true
},
polylineOptions: {
editable: true
},
rectangleOptions: polyOptions,
circleOptions: polyOptions,
polygonOptions: polyOptions,
map: map
});
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
if (e.type != google.maps.drawing.OverlayType.MARKER) {
// Switch back to non-drawing mode after drawing a shape.
drawingManager.setDrawingMode(null);
// Add an event listener that selects the newly-drawn shape when the user
// mouses down on it.
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, 'click', function() {
setSelection(newShape);
});
setSelection(newShape);
}
});
// Clear the current selection when the drawing mode is changed, or when the
// map is clicked.
google.maps.event.addListener(drawingManager, 'drawingmode_changed', clearSelection);
google.maps.event.addListener(map, 'click', clearSelection);
google.maps.event.addDomListener(document.getElementById('delete-button'), 'click', deleteSelectedShape);
buildColorPalette();
}
google.maps.event.addDomListener(window, 'load', initialize);

Multiple polylines and infowindows with Google Maps V3

I have a map with multiple polylines and would like to open a line-specific-infowindow when clicking the line.
So far my code only shows the content of the last iteration.
I found two very nice examples of what I want but after hours of trying I am still no further.
Example 1: http://srsz750.appspot.com/api3/polylines-multiple.html
Example 2: http://www.geocodezip.com/v3_GenericMapBrowser.asp?filename=flights090414.xml
So your are my last shot :-S
Here is my code that shows only the content of the last iteration:
for (var i = 0; i < locations.length; i++) {
var route = locations[i]; // locations is an array of route-arrays.
//route is an array with details. route[0] contains the description.
var imageStart = 'img/rijder.png';
var polyOptions = {
strokeColor: '#0000FF',
strokeOpacity: 1.0,
strokeWeight: 3
}
poly = new google.maps.Polyline(polyOptions, info);
var path = poly.getPath();
//line text
var info = route[0];
google.maps.event.addListener(poly, 'click', function(event) {
infowindow.setContent(info);
infowindow.position = event.latLng;
infowindow.open(map);
});
//startmarker
var startLatLng = new google.maps.LatLng(route[1], route[2]);
var smarker = new google.maps.Marker({
position: startLatLng,
map: map,
icon: imageStart,
title: route[7],
html: route[0]
});
path.push(startLatLng);
//starttext
google.maps.event.addListener(smarker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
//endmarker
var endLatLng = new google.maps.LatLng(route[4], route[5]);
var emarker = new google.maps.Marker({
position: endLatLng,
map: map,
icon: imageEnd,
title: route[8],
html: route[3]
});
path.push(endLatLng);
//endtext
google.maps.event.addListener(emarker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
//close line and put on the map
poly.setMap(map);
}
}
And here is the code I would expect to work but all lines disappeared (only the relevant code, I also added a mouseover function):
//line text
google.maps.event.addListener(poly, 'click', (function(event,index){
return function(){
var routeinfw = locations[index];
var inf = routeinfw[0];
infowindow.setContent(inf);
infowindow.position = mouselocation;
infowindow.open(map);
};
})(event,i));
//starticon
Just like in the example you posted, create a function to create the click events listeners and call it from inside the locations loop:
function createInfoWindow(poly,content) {
google.maps.event.addListener(poly, 'click', function(event) {
infowindow.content = content;
infowindow.position = event.latLng;
infowindow.open(map);
});
}
And you can call this at the end of the loop:
createInfoWindow(poly,info);