How do I capture point locations of Polygon with Google Maps API? - javascript

Using the Google Maps API Drawing Manager, I want to collect the location of each point in the polygon that is drawn by a user.
I know there is a getPath() function, but I'm not sure where I use it.
This is all the code I have so far:
var map; var drawingManager;
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(45.13536, -100.762952),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: false,
polygonOptions: {
fillColor: "#000000",
fillOpacity: .6,
strokeWeight: 1,
strokeColor: "#666666",
clickable: false,
editable: true,
zIndex: 1
}
});
drawingManager.setMap(map);
google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {
drawingManager.setDrawingMode(null);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
So from this code, how can I use the getPath() function to show the coordinates that make up the Polygon that is drawn?

use it inside the polygoncomplete-callback.
example:
google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {
drawingManager.setDrawingMode(null);
var arr=[];
polygon.getPath().forEach(function(latLng){arr.push(latLng.toString());})
alert(arr.join(',\n'));
});
it iterates over the path(using the forEach-method of a google.maps.MVCArray) and populates another array with the string-representations of the LatLng's

Related

Edit and save updated polygon coordinates in google maps

In my rails application I have implemented a google maps using the polygon drawing tool. I have been able to add coordinates and save these to my database successfully.
The problem i'm having is when a user wants to edit and save any changes made to the polygon shape. How do i implement this function? My best guess is to use a conditional to see if the database has any saved coordinates, if so, load them in a listener?
HTML
<div style='width: 100%;'>
<%= hidden_field_tag(:map_coords, value = nil, html_options = {id: 'propertyCoordinates'}) %>
Javascript
function initMap() {
var map = new google.maps.Map(document.getElementById("map"), {
center: { lat: -40.6892, lng: 74.0445 },
zoom: 8,
mapTypeId: google.maps.MapTypeId.HYBRID,
});
var polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35
};
// loads databased saved coordinates
var propertyCoords = [<%= #property.coordinates %>];
var points = [];
for (var i = 0; i < propertyCoords.length; i++) {
points.push({
lat: propertyCoords[i][0],
lng: propertyCoords[i][1]
});
}
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: ["polygon"]
},
polylineOptions: {
editable: true,
draggable: true
},
rectangleOptions: polyOptions,
circleOptions: polyOptions,
polygonOptions: polyOptions,
map: map
});
if (typeof points !== 'undefined') {
// My guess is to use a conditional statement to check if the map has any coordinates saved?
} else {
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 (e) {
if (e.vertex !== undefined) {
if (newShape.type === google.maps.drawing.OverlayType.POLYGON) {
var path = newShape.getPaths().getAt(e.path);
path.removeAt(e.vertex);
if (path.length < 3) {
newShape.setMap(null);
}
}
}
setSelection(newShape);
});
}
var coords = e.overlay.getPath().getArray();
document.getElementById("propertyCoordinates").value = coords;
});
}
} // END function initMap()
If I understand correctly, what you're looking for is the polygon editing functionality. My stackblitz example goes something like this:
Draw a polygon if you already have user-saved coordinates. Then fit the map bounds to the poly's bounds. For this you'll probably need a getBounds polyfill.
Make the polygon editable so you can listen to its points' changes. Check the function enableCoordinatesChangedEvent.
Listen to the changes & extract the new polygon points. Look for function extractPolygonPoints.
Then proceed with your business logic.
FYI you'll need to put your own API key at the bottom of the stackblitz index.html. Look for YOUR_KEY.

Drawing a POLYGON from initial position

My problem is: I need to draw with mode POLYGON with a initial point, like a marker or another element. For example - JSFiddle Example
With marker:
var initialPosition = new google.maps.Marker({
position: {
lat: -22.397542,
lng: -46.884630
}
});
This position is given without any user interaction. How can I do that?
In my example, how can I draw a polygon starting from marker without click it, making marker position my first polygon point?
You could do the following: use addListenerOnce to detect a click on the map (only once). This will allow to create a Polygon that goes from your marker position, to where the user clicked, and back to the marker position.
By setting the editable property to true, you can then move each Polygon point separately, and add segments by dragging the existing segment(s) middle point(s).
Here is a working example:
function initialize() {
var myLatLng = new google.maps.LatLng(46.2, 6.17);
var mapOptions = {
zoom: 4,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var marker = new google.maps.Marker({
position: myLatLng,
map: map
});
google.maps.event.addListenerOnce(map, 'click', function(e) {
var origin = marker.getPosition();
var coords = [
origin,
e.latLng,
origin,
];
var poly = new google.maps.Polygon({
map: map,
paths: coords,
editable: true,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
});
}
initialize();
#map-canvas {
height: 150px;
}
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js"></script>

Google Maps Engine API - KML Layers Obstructing New Markers Event

I am currently building out a small widget that allows someone to see a kml heat map of the united states population density then select an area on that map and drop a market on to that location. The user then enters a number and that creates a mile radius to show the user how much area they cover.
My problem is that I have 63 .kml files for just one state in the US. I know I can remove the xml <name> and <description> to prevent the name from popping up when clicked, but I can't see that being practical with that many .kml files.
Is there a programmatic solution or API solution to prevent just the kml layers from being clickable?
var citymap = {};
citymap['chicago'] = {
center: new google.maps.LatLng(41.878113, -87.629798),
value: 2714856
};
citymap['newyork'] = {
center: new google.maps.LatLng(40.714352, -74.005973),
value: 8405837
};
citymap['losangeles'] = {
center: new google.maps.LatLng(34.052234, -118.243684),
value: 3857799
};
citymap['vancouver'] = {
center: new google.maps.LatLng(49.25, -123.1),
value: 603502
};
var cityCircle;
function initialize() {
// Create the map.
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(34.7361, -92.3311),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Construct the circle for each value in citymap.
// Note: We scale the area of the circle based on the population.
for (var city in citymap) {
var populationOptions = {
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: citymap[city].center,
radius: Math.sqrt(citymap[city].value) * 100
};
// Add the circle for this city to the map.
cityCircle = new google.maps.Circle(populationOptions);
}
var ctaLayer = new google.maps.KmlLayer({
url: 'http://www.census.gov/main/kml/countysubs_z6/AR/05003.xml'
});
ctaLayer.setMap(map);
google.maps.event.addListener(map, 'click', function(e) {
placeMarker(e.latLng, map);
});
}
function placeMarker(position, map) {
var marker = new google.maps.Marker({
position: position,
map: map
});
map.panTo(position);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<div id="map-canvas"></div>
Discretionary note: Google API does not work well with Stack Overflow's code snippet's widget.
set the KmlLayer clickable option to false
clickable boolean If true, the layer receives mouse events. Default value is true.
var citymap = {};
citymap['chicago'] = {
center: new google.maps.LatLng(41.878113, -87.629798),
value: 2714856
};
citymap['newyork'] = {
center: new google.maps.LatLng(40.714352, -74.005973),
value: 8405837
};
citymap['losangeles'] = {
center: new google.maps.LatLng(34.052234, -118.243684),
value: 3857799
};
citymap['vancouver'] = {
center: new google.maps.LatLng(49.25, -123.1),
value: 603502
};
var cityCircle;
function initialize() {
// Create the map.
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(34.7361, -92.3311),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Construct the circle for each value in citymap.
// Note: We scale the area of the circle based on the population.
for (var city in citymap) {
var populationOptions = {
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: citymap[city].center,
radius: Math.sqrt(citymap[city].value) * 100
};
// Add the circle for this city to the map.
cityCircle = new google.maps.Circle(populationOptions);
}
var ctaLayer = new google.maps.KmlLayer({
url: 'http://www.census.gov/main/kml/countysubs_z6/AR/05003.xml',
clickable: false
});
ctaLayer.setMap(map);
google.maps.event.addListener(map, 'click', function(e) {
placeMarker(e.latLng, map);
});
}
function placeMarker(position, map) {
var marker = new google.maps.Marker({
position: position,
map: map
});
map.panTo(position);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>

Google Map Circle for single address not working

I am trying to get a single circle for my google map, i am not using the multiple array as it is specified in the google map document because i just want one single point with the circle to be shown in the map.
I don't know where exactly am i making error, please will someone let me know where exactly am i making error.
this is my code
var loc = new google.maps.LatLng(25.800693, 55.976199);
var marker;
var map;
function initialize() {
var mapOptions = {
zoom: 15,
center: loc
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
marker = new google.maps.Marker({
map: map,
draggable: true,
animation: google.maps.Animation.DROP,
position: loc
});
google.maps.event.addListener(marker, 'click', toggleBounce);
}
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
cityCircle = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: new google.maps.LatLng(25.800693, 55.976199),
radius: 50
});
google.maps.event.addDomListener(window, 'load', initialize);
Thanks in advance
Move the initialization of the circle inside the initialize function, so it is initialized after the map, not before.
var loc = new google.maps.LatLng(25.800693, 55.976199);
var marker;
var map;
function initialize() {
var mapOptions = {
zoom: 15,
center: loc
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
marker = new google.maps.Marker({
map: map,
draggable: true,
animation: google.maps.Animation.DROP,
position: loc
});
cityCircle = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: new google.maps.LatLng(25.800693, 55.976199),
radius: 50
});
google.maps.event.addListener(marker, 'click', toggleBounce);
}
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>

google map api v3 - how to limit number of polygon lines and force closure at the 5 click?

i have this code
<script>
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.MARKER,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
google.maps.drawing.OverlayType.POLYGON
]
},
polygonOptions: {
draggable: true,
editable: true,
strokeColor: "#000",
strokeWeight: "2"
}
});
drawingManager.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
And i am trying to limit the number of polygon lines to 5 and by the 5 click to force closure of the polygon shape.
I was unable to find any direction to solve this problem.. if u have any link to good resource or ideas how to - that would be good!
One option: don't use the DrawingManager. Build the polygon yourself and keep track of the markers added.
var poly;
var map;
function initialize() {
var polyOptions = {
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3, map: map
};
poly = new google.maps.Polygon(polyOptions);
var bounds = new google.maps.LatLngBounds();
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: new google.maps.LatLng(10.9386, -84.888),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var evtListnr = google.maps.event.addListener(map,"click",function(evt) {
bounds.extend(evt.latLng);
addLatLng(evt);
if (poly.getPath().getLength() == 5) {
google.maps.event.removeListener(evtListnr);
}
});
poly.binder = new MVCArrayBinder(poly.getPath());
poly.setMap(map);
}
proof of concept

Categories

Resources