How to find which polygon selected in google maps api - google-maps

Hi I'm New to Google maps Api , I created polygons in google maps, i want to find out which polygon i clicked, I tried but i'm not able to find out , here is my code
function initialize() {
var mapOptions = {
zoom: 14,
center: new google.maps.LatLng(12.9648451,77.5741997),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var arr = new Array();
var polygons = [];
var bounds = new google.maps.LatLngBounds();
var coordinates = [];
// downloadUrl("subdivision-coordinates.php", function(data) {
var xmlString = '<subdivisions><subdivision name="Auburn Hills"><coord lat="12.973111130721453" lng="77.54373550415039"/><coord lat="12.929112653428087" lng="77.53360748291016"/><coord lat="12.936306851970127" lng="77.57635116577148"/></subdivision><subdivision name="Vanderveen"><coord lat="12.97227473026135" lng="77.59489059448242"/><coord lat="12.952200275819832" lng="77.58750915527344"/><coord lat="12.95487696326559" lng="77.60536193847656"/></subdivision></subdivisions>';
//var xmlString =$('#xml_values').val();
var xml = xmlParse(xmlString);
var subdivision = xml.getElementsByTagName("subdivision");
for (var i = 0; i < subdivision.length; i++) {
arr = [];
var coordinates = xml.documentElement.getElementsByTagName("subdivision")[i].getElementsByTagName("coord");
//console.log("coordinates="+xml.documentElement.getElementsByTagName("subdivision")[i].getElementsByTagName("coord"));
for (var j=0; j < coordinates.length; j++) {
arr.push(new google.maps.LatLng(
parseFloat(coordinates[j].getAttribute("lat")),
parseFloat(coordinates[j].getAttribute("lng"))
));
bounds.extend(arr[arr.length-1])
//console.log("arr lenghth="+arr.length+"___"+arr[arr.length-1]+"|___|"+coordinates[j])
}
polygons.push(new google.maps.Polygon({
paths: arr,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
}));
polygons[polygons.length-1].setMap(map);
google.maps.event.addListener(polygons[polygons.length-1], 'click', function (event) {
alert(JSON.stringify(event));
});
}
map.fitBounds(bounds);
function xmlParse(str) {
if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
}
if (typeof DOMParser != 'undefined') {
return (new DOMParser()).parseFromString(str, 'text/xml');
}
return createElement('div', null);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
How to identify which polygon is clicked using polygon number in google maps api

When you create the polygon, add an additional property to identify the polygon, e.g.
polygons.push(new google.maps.Polygon({
id: i,
paths: arr,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
}));
Then in your event listener, you should be able to get this from the this scope of that polygon:
polygons[polygons.length-1].addListener('click', function (event) {
console.log(this.id);
});

Related

Create Polygon on Google Maps with JSON of openstreetmap. InvalidValueError: not an Array

I want to show the border between provinces in google maps. In forums it is said that the only way is to call openstreetmap to obtain coordinates, and then create a polygon in Google maps. The code fails, don´t show Polygon and give "InvalidValueError: not an Array". Is it because of the promise call? or because, I do not generate the array well?
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
// TNF
zoom: 10,
center: {lat: 28.4125202, lng: -16.5566306},
mapTypeId: 'roadmap'
});
var promise = $.getJSON('https://nominatim.openstreetmap.org/details.php?place_id=256937694&polygon_geojson=1&format=json');
promise.then(function(data){
var cachedGeoJson = data; //save the geojson in case we want to update its values
console.log(JSON.stringify(cachedGeoJson)); //OUTPUT-1
console.log(cachedGeoJson.geometry.coordinates); // OUTPUT-2
for (var i = 0; i < cachedGeoJson.geometry.coordinates.length; i++) {
var coord = cachedGeoJson.geometry.coordinates[i];
coord_poligon.push(coord);
};
coord_poligon_JSON = JSON.stringify(coord_poligon);
console.log(coord_poligon_JSON ); // OUTPUT-3:
var geoObject = cachedGeoJson.geometry.coordinates;
var features = [];
features = geoObject;
var geoJson = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates":features,
},
"properties": {}
}]
};
console.log(JSON.stringify(geoJson)); // OUTPUT-4
}); // end promise.
// Construct the polygon.
triangleCoords = geoJson;
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#ea0e0e', // red color
fillOpacity: 0.20
});
bermudaTriangle.setMap(map);
//OUTPUT-1:
//{"place_id":256937694,...
//{"type":"Point","coordinates":[-16.5532956,28.4159024]},"geometry":{"type":"Polygon","coordinates":[[[-16.5705013,28.4080941],[-16.5703805,28.4076554],...
// OUTPUT-2:
//0: (2) [-16.5705013, 28.4080941]
//1: (2) [-16.5703805, 28.4076554]
//2: (2) [-16.5701851, 28.4064929]
// OUTPUT-3: [[[-16.5705013,28.4080941],[-16.5703805,28.4076554],[-16.5701851,28.4064929],...
// OUTPUT-4: {"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[-16.5705013,28.4080941],[-16.5703805,28.4076554],
Finally I used the Polygon array, not geoJson. About that: openstreetmap return (lng,lat). It is the reverse order that the Google Maps API needs to create POLYGON, that uses it (lat,lng) so:
1-STEP: you have to change the coordinate pair order, that´s create a new array with coordenate pairs (lat,lng):
'''
var promise = $.getJSON('https://nominatim.openstreetmap.org/details.php?place_id=256937694&polygon_geojson=1&format=json');
promise.then(function(data){
var cachedGeoJson = data;
for (var i = 0; i < cachedGeoJson.geometry.coordinates.length; i++) {
var lnglat = cachedGeoJson.geometry.coordinates[i];
for(var j = 0; j < lnglat.length; j++)
{
var longitud = lnglat[j][0]; // first value on openstreetmap is lng
var latitud = lnglat[j][1]; // second value is lat
coord_poligon.push(new google.maps.LatLng(parseFloat(latitud), parseFloat(longitud )));
}
};
'''
2-STEP: to assign this new array (lat,lng) to array that will create the POLYGON:
'''
var triangleCoords = [coord_poligon]; //array inside brackets. IMPORTANT!
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords, // array
strokeColor: '#0a6df0', // azul oscuro
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#48cef7', // azul claro
fillOpacity: 0.20
});
bermudaTriangle.setMap(map);
infoWindow = new google.maps.InfoWindow;
}); // end promise.
'''
COMPLETE CODE:
'''
var coord_poligon = [];
var triangleCoords = [];
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 28.4125202, lng: -16.5566306}, // TNF
mapTypeId: 'roadmap'
});
var promise = $.getJSON('https://nominatim.openstreetmap.org/details.php?place_id=256937694&polygon_geojson=1&format=json');
promise.then(function(data){
var cachedGeoJson = data;
for (var i = 0; i < cachedGeoJson.geometry.coordinates.length; i++) {
var lnglat = cachedGeoJson.geometry.coordinates[i];
for(var j = 0; j < lnglat.length; j++)
{
var longitud = lnglat[j][0]; // first value on opentreet is lng
var latitud = lnglat[j][1]; // second value is lat
coord_poligon.push(new google.maps.LatLng(parseFloat(latitud), parseFloat(longitud )));
}
};
var triangleCoords = [coord_poligon]; // array dentro de corchetes . IMPORTANT!
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords, // array
strokeColor: '#0a6df0', // dark blue
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#48cef7', // blue
fillOpacity: 0.20
});
bermudaTriangle.setMap(map);
infoWindow = new google.maps.InfoWindow;
}); // end promise.
} // end initMap()
'''

map does not display without domlistner

i want to draw a polygon on the trigger of certain function. i have created a button submit which initiate the insert function which got coordinates from the user and call display function.
var map; var triangleCoords = [];
function insert() {
//var markerImage = 'assets/img/marker.png';
// var marker = new google.maps.Marker({
// position: location,
// map: map,
// icon: markerImage
// });
triangleCoords = [
[30.983611, 73.332778],
[30.93361111, 73.33055556],
[30.93361111, 73.43055556],
[30.98111111, 73.42944444]
];
display();
}
function display()
{
function initMap() {
var location = new google.maps.LatLng(31.1704, 72.7097);
var mapCanvas = document.getElementById('map');
var mapOptions = {
center: location,
zoom: 7,
panControl: false
// mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(mapCanvas, mapOptions);
var points = [];
for (var i = 0; i < triangleCoords.length; i++) {
points.push({
lat: triangleCoords[i][0],
lng: triangleCoords[i][1]
});
}
// Construct the polygon.
var bermudaTriangle = new google.maps.Polygon({
paths: points,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
zoom: 13,
fillColor: '#FF0000',
fillOpacity: 0.35
});
bermudaTriangle.setMap(map);
}
google.maps.event.addDomListener(window,'load',initMap);
}
code is working fine but if i remove google.maps.event.addDomListener(window,'load',initMap); line map doesnot display. my submit button clears the forms.

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 - draw multiple separate polylines

So I am trying to draw multiple separated polylines on google map.
So far I don't have so much:
<script>
var center = new google.maps.LatLng(51.97559, 4.12565);
var map = new google.maps.Map(document.getElementById('map'), {
center: center,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow({
map: map
});
var bounds = new google.maps.LatLngBounds();
// start coordinates
var start = ['51.97559, 4.12565',
'55.46242, 8.43872',
'49.49259, 0.1065',
'50.36862, -4.13412']
// end coordinates
var end = ['51.94784, 1.2539',
'51.74784, 1.2539',
'50.79726, -1.11048',
'43.45846, -3.80685']
function initialize() {
for (var i=0; i < end.length; i++){
calcRoute(start[i], end [i]);
}
}
function calcRoute(source,destination){
var polyline = new google.maps.Polyline({
path: [],
strokeColor: 'red',
strokeWeight: 2,
strokeOpacity: 1
});
polyline.setMap(map);
}
</script>
I found here an interesting example, but it has DirectionsTravelMode, and I want only a straight line between two points.
So in my example I would like to have 4 not connected straight lines drawn on the map.
a google.maps.LatLng object is two numbers; or a google.maps.LatLngLiteral is a javascript object with a lat and a lng property, neither is a string.
for (var i=0; i < end.length; i++){
var startCoords = start[i].split(",");
var startPt = new google.maps.LatLng(startCoords[0],startCoords[1]);
var endCoords = end[i].split(",");
var endPt = new google.maps.LatLng(endCoords[0],endCoords[1]);
calcRoute(startPt, endPt);
bounds.extend(startPt);
bounds.extend(endPt);
}
map.fitBounds(bounds);
you need to add those to the polyline's path:
function calcRoute(source,destination){
var polyline = new google.maps.Polyline({
path: [source, destination],
strokeColor: 'red',
strokeWeight: 2,
strokeOpacity: 1
});
polyline.setMap(map);
}
proof of concept fiddle
code snippet:
var map;
function initialize() {
var center = new google.maps.LatLng(51.97559, 4.12565);
map = new google.maps.Map(document.getElementById('map'), {
center: center,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow({});
var bounds = new google.maps.LatLngBounds();
// start coordinates
var start = ['51.97559, 4.12565',
'55.46242, 8.43872',
'49.49259, 0.1065',
'50.36862, -4.13412'
]
// end coordinates
var end = ['51.94784, 1.2539',
'51.74784, 1.2539',
'50.79726, -1.11048',
'43.45846, -3.80685'
]
for (var i = 0; i < end.length; i++) {
var startCoords = start[i].split(",");
var startPt = new google.maps.LatLng(startCoords[0], startCoords[1]);
var endCoords = end[i].split(",");
var endPt = new google.maps.LatLng(endCoords[0], endCoords[1]);
calcRoute(startPt, endPt);
bounds.extend(startPt);
bounds.extend(endPt);
}
map.fitBounds(bounds);
}
function calcRoute(source, destination) {
var polyline = new google.maps.Polyline({
path: [source, destination],
strokeColor: 'red',
strokeWeight: 2,
strokeOpacity: 1
});
polyline.setMap(map);
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
Nice answer by geocodezip !
A small improvement, instead of adding many polyline elements to your map (which could later require you to keep track of them & iterate over all of them in order to remove or change them), you can put all paths in one Polygon object.
working fiddle: http://jsfiddle.net/syoels/hyh81jfz/1/
(i took geocodezip's fiddle and made small changes)
var geocoder;
var map;
function initialize() {
var center = new google.maps.LatLng(51.97559, 4.12565);
map = new google.maps.Map(document.getElementById('map'), {
center: center,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var bounds = new google.maps.LatLngBounds();
// start coordinates
var start = ['51.97559, 4.12565',
'55.46242, 8.43872',
'49.49259, 0.1065',
'50.36862, -4.13412'
];
// end coordinates
var end = ['51.94784, 1.2539',
'51.74784, 1.2539',
'50.79726, -1.11048',
'43.45846, -3.80685'
];
var paths = [];
for (var i = 0; i < end.length; i++) {
var startCoords = start[i].split(",");
var startPt = new google.maps.LatLng(startCoords[0], startCoords[1]);
var endCoords = end[i].split(",");
var endPt = new google.maps.LatLng(endCoords[0], endCoords[1]);
paths.push([startPt, endPt]);
bounds.extend(startPt);
bounds.extend(endPt);
}
map.fitBounds(bounds);
var polyline = new google.maps.Polygon({
paths: paths,
strokeColor: 'red',
strokeWeight: 2,
strokeOpacity: 1
});
polyline.setMap(map);
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,places&ext=.js"></script>
<div id="map"></div>

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