Reputation: 1452
I need to draw polygon using mouse and mark a particular area on Google maps. The purpose is to mark an area on Google maps and then showing hotels and attractions on that area. The user will mark the hotels on Google map while creating them so the db will have their latitude and longitudes.
How can I draw the polygon and fill it with a color as background to mark the area in Google Maps? I have read the API Manual “how to draw polygons?” basically you would need to mark multiple points and then combine them into a polygon. But I will need to do this using mouse drag, just like drawing a shape. Kindly help me out how to achieve this.
Upvotes: 36
Views: 101051
Reputation: 2119
Google My Maps Creates new map than create new layer than import new excel file in the excel file you can write you WKT
[
{
"WKT": "POLYGON ((100.01397525354281 50, 100.0137067229647 49.99727356328608, 100.01291145070986 49.99465190200606, 100.01161999864507 49.99223576513271, 100.00988199654893 49.99011800345108, 100.00776423486728 49.988380001354926, 100.00534809799393 49.98708854929014, 100.00272643671393 49.98629327703531, 100 49.98602474645719, 99.99727356328607 49.98629327703531, 99.99465190200607 49.98708854929014, 99.99223576513272 49.988380001354926, 99.99011800345107 49.99011800345108, 99.98838000135493 49.99223576513271, 99.98708854929014 49.99465190200606, 99.9862932770353 49.99727356328608, 99.98602474645719 50, 99.9862932770353 50.00272643671392, 99.98708854929014 50.00534809799394, 99.98838000135493 50.00776423486729, 99.99011800345107 50.00988199654892, 99.99223576513272 50.011619998645074, 99.99465190200607 50.01291145070986, 99.99727356328607 50.01370672296469, 100 50.01397525354281, 100.00272643671393 50.01370672296469, 100.00534809799393 50.01291145070986, 100.00776423486728 50.011619998645074, 100.00988199654893 50.00988199654892, 100.01161999864507 50.00776423486729, 100.01291145070986 50.00534809799394, 100.0137067229647 50.00272643671392, 100.01397525354281 50))",
"name": "Circle",
"description": "radius 1000 meters"
},
{
"WKT": "POLYGON ((100.01397525354281 50.01397525354281, 100.01397525354281 49.98602474645719, 99.98602474645719 49.98602474645719, 99.98602474645719 50.01397525354281, 100.01397525354281 50.01397525354281))",
"name": "Rectangle",
"description": ""
},
{
"WKT": "POLYGON ((100.01976399309784 50, 100.01938423351235 49.996144236222214, 100.0182595487038 49.99243664728408, 100.01643315967861 49.98901971374923, 100.01397525354281 49.98602474645719, 100.01098028625077 49.98356684032139, 100.00756335271592 49.981740451296204, 100.00385576377778 49.980615766487645, 100 49.98023600690215, 99.99614423622222 49.980615766487645, 99.99243664728408 49.981740451296204, 99.98901971374923 49.98356684032139, 99.98602474645719 49.98602474645719, 99.98356684032139 49.98901971374923, 99.9817404512962 49.99243664728408, 99.98061576648765 49.996144236222214, 99.98023600690216 50, 99.98061576648765 50.003855763777786, 99.9817404512962 50.00756335271592, 99.98356684032139 50.01098028625077, 99.98602474645719 50.01397525354281, 99.98901971374923 50.01643315967861, 99.99243664728408 50.018259548703796, 99.99614423622222 50.019384233512355, 100 50.01976399309785, 100.00385576377778 50.019384233512355, 100.00756335271592 50.018259548703796, 100.01098028625077 50.01643315967861, 100.01397525354281 50.01397525354281, 100.01643315967861 50.01098028625077, 100.0182595487038 50.00756335271592, 100.01938423351235 50.003855763777786, 100.01976399309784 50))",
"name": "Circle"
}
]
Upvotes: 0
Reputation: 1591
I have used following code to draw polygon on a map
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<title>Drawing Tools</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=drawing"></script>
<style type="text/css">
#map, html, body {
padding: 0;
margin: 0;
height: 100%;
}
#panel {
width: 200px;
font-family: Arial, sans-serif;
font-size: 13px;
float: right;
margin: 10px;
}
#color-palette {
clear: both;
}
.color-button {
width: 14px;
height: 14px;
font-size: 0;
margin: 2px;
float: left;
cursor: pointer;
}
#delete-button {
margin-top: 5px;
}
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
</style>
<script type="text/javascript">
var geocoder;
var map;
var all_overlays = [];
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true,
fillColor: '#FF1493'
};
var selectedShape;
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: false,
markerOptions: {
draggable: true
},
polygonOptions: polyOptions
});
$('#enablePolygon').click(function() {
drawingManager.setMap(map);
drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYGON);
});
$('#resetPolygon').click(function() {
if (selectedShape) {
selectedShape.setMap(null);
}
drawingManager.setMap(null);
$('#showonPolygon').hide();
$('#resetPolygon').hide();
});
google.maps.event.addListener(drawingManager, 'polygoncomplete',
function(polygon) {
// var area = google.maps.geometry.spherical.computeArea(selectedShape.getPath());
// $('#areaPolygon').html(area.toFixed(2)+' Sq meters');
$('#resetPolygon').show();
});
function clearSelection() {
if (selectedShape) {
selectedShape.setEditable(false);
selectedShape = null;
}
}
function setSelection(shape) {
clearSelection();
selectedShape = shape;
shape.setEditable(true);
}
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
all_overlays.push(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);
}
});
google.maps.event.addListener(drawingManager, 'polygoncomplete', function (polygon) {
var coordinates = (polygon.getPath().getArray());
console.log(coordinates);
alert(coordinates);
});
}
google.maps.event.addDomListener(window, "load", initialize);
</script>
</head>
<body>
<input type="button" id="enablePolygon" value="Calculate Area" />
<input type="button" id="resetPolygon" value="Reset" style="display: none;" />
<div id="showonPolygon" style="display:none;"><b>Area:</b> <span
id="areaPolygon"> </span></div>
<div id="map_canvas"></div>
</html>
Upvotes: 2
Reputation: 327
i made an example for myself. the code is below and also jsfiddle is avaible
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=drawing&callback=initMap" async defer></script>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 8
});
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: false,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: ['polygon', 'circle']
},
polygonOptions: {
editable: true
}
});
drawingManager.setMap(map);
google.maps.event.addListener(drawingManager, 'overlaycomplete',
function(event) {
event.overlay.set('editable', false);
drawingManager.setMap(null);
console.log(event.overlay);
});
}
</script>
https://jsfiddle.net/zgmdvsrz/
you can set drawingcontrol to true if you want to show drawing manager
Upvotes: 7
Reputation: 3997
There have been some significant improvements in google.maps.polygon since this question was first asked. Here's a simple implementation, using all native google.maps v3 tools. (Note: there is a wonky JavaScript scope work around here... but it does work...)
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);
myMvcArray.getArray().forEach(function(value, index) {
console.log(" index: " + index + " value: " + value);
})
});
});
Answer with new code submitted on old question in case anybody else gets here!
Upvotes: 1
Reputation: 344261
You may want to check out the Geometry Controls of the GMaps Utility Library.
For further reference, you may want to go through the GeometryControls Reference.
Upvotes: 9
Reputation: 2334
The new Map Engines Lite is exactly the tool you're looking for I think: https://mapsengine.google.com/map/
Upvotes: 4
Reputation: 1156
There is a port of the API v2 drawing tools to API v3 @ http://nettique.free.fr/gmap/toolbar.html
Upvotes: 1
Reputation: 4568
The Google Maps JavaScript API v3 provides a drawing library, http://code.google.com/apis/maps/documentation/javascript/overlays.html#drawing_tools
You just need to enable the drawing tools (as shown the the example in the docs) and add event listeners for the creation of overlay types (as shown under the "Drawing Events" section).
A quick example of its use would be: http://gmaps-samples-v3.googlecode.com/svn/trunk/drawing/drawing-tools.html
Upvotes: 21
Reputation: 310802
Here is some code (for the Google Maps JavaScript API version 3) that achieves what you want. It supports:
It's undocumented, but hopefully you can see what it's doing easily enough.
$(document).ready(function () {
var map = new google.maps.Map(document.getElementById('map'), { center: new google.maps.LatLng(21.17, -86.66), zoom: 9, mapTypeId: google.maps.MapTypeId.HYBRID, scaleControl: true });
var isClosed = false;
var poly = new google.maps.Polyline({ map: map, path: [], strokeColor: "#FF0000", strokeOpacity: 1.0, strokeWeight: 2 });
google.maps.event.addListener(map, 'click', function (clickEvent) {
if (isClosed)
return;
var markerIndex = poly.getPath().length;
var isFirstMarker = markerIndex === 0;
var marker = new google.maps.Marker({ map: map, position: clickEvent.latLng, draggable: true });
if (isFirstMarker) {
google.maps.event.addListener(marker, 'click', function () {
if (isClosed)
return;
var path = poly.getPath();
poly.setMap(null);
poly = new google.maps.Polygon({ map: map, path: path, strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FF0000", fillOpacity: 0.35 });
isClosed = true;
});
}
google.maps.event.addListener(marker, 'drag', function (dragEvent) {
poly.getPath().setAt(markerIndex, dragEvent.latLng);
});
poly.getPath().push(clickEvent.latLng);
});
});
Upvotes: 32
Reputation: 248
you can use the Google MyMaps polygon editing tools in your appplication, maybe this will be ok for you?
see http://googlemapsapi.blogspot.com/2008/05/love-my-maps-use-its-line-and-shape.html
However if you want to implement this yourself it is basically this:
add click listener to map.
repeat: store points that user clicks on in an array, and add a marker at this point. if it is the first marker add click listener to it
when user clicks on first marker, parse use the array of points to build your polygon
I don't have any code to show you, but I have implemented this myself in a previous company, so it can be done :)
Upvotes: 19