Easiest way to calculate area of drawn polygon with google map - javascript

Javascript/google maps beginner here.
I am looking for a simple way to calculate the area of a polygon the user draws on the map.
Code Snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 53,
lng: 0
},
zoom: 13
});
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.MARKER,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: ['polygon']
},
circleOptions: {
fillColor: '#ffff00',
fillOpacity: 1,
strokeWeight: 5,
clickable: false,
editable: true,
zIndex: 1
}
});
drawingManager.setMap(map);
}
<div>
<div id="map" style="width: 100%; height: 500px;"></div>
</div>

Use the google.maps.geometry.spherical.computeArea method
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {
var area = google.maps.geometry.spherical.computeArea(polygon.getPath());
infowindow.setContent("polygon area="+area.toFixed(2)+" sq meters");
infowindow.setPosition(polygon.getPath().getAt(0));
infowindow.open(map);
});
proof of concept fiddle
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 53.000581,
lng: -0.005
},
zoom: 19
});
var infowindow = new google.maps.InfoWindow();
var polygon = new google.maps.Polygon({
path: [{lat: 53.000842,lng: -0.004903},
{lat: 53.000823,lng: -0.004798},
{lat: 53.000779,lng: -0.004823},
{lat: 53.000799,lng: -0.004935}],
map: map
});
var area = google.maps.geometry.spherical.computeArea(polygon.getPath());
infowindow.setContent("polygon area=" + area.toFixed(2) + " sq meters");
infowindow.setPosition(polygon.getPath().getAt(0));
infowindow.open(map);
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.MARKER,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: ['polygon']
},
drawingMode: null
});
google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {
var area = google.maps.geometry.spherical.computeArea(polygon.getPath());
infowindow.setContent("polygon area=" + area.toFixed(2) + " sq meters");
infowindow.setPosition(polygon.getPath().getAt(0));
infowindow.open(map);
});
drawingManager.setMap(map);
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,drawing&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map"></div>

Related

Google map is displaying only when its size get resized

I am loading google map in my webpage with some width and height.Here is my code:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
//google.maps.event.trigger(map, 'resize');
/*$(window).resize(function() {
google.maps.event.trigger(map, "resize");
});*/
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.MARKER,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: ['polygon', 'polyline']
},
circleOptions: {
strokeColor: '#00DB00',
fillColor: 'green'
}
});
drawingManager.setMap(map);
}
style:
#map{
width:500px;
height:300px;
}
html:
<div class="cl col-xs-12 col-sm-6 col-md-6 col-lg-6">
<div id="map"></div>
</div>
When I load the page,map is displaying like this
After resizing the map its displaying correctly.
What is the problem here?
I think you're missing the drawingManager.setMap(map); at the end of your initMap function.

Remove Polygon On Second Click

When the user clicks on the marker the first time I want a polygon to appear. The second time they click the polygon should disappear. This code works fine for the appearing part but it does not remove the polygon from the map. Every odd click just makes the polygon darker.
body onload="initMap()">
<p id="instructions"></p>
<div id="map" style='overflow:hidden;height:500px;width:500px;'></div>
<script type="text/javascript">
function initMap() {
var myOptions = {zoom:11,center:new google.maps.LatLng(37.55020520861464,126.98140242753904),mapTypeId: google.maps.MapTypeId.ROADMAP};
map = new google.maps.Map(document.getElementById('map'), myOptions);
document.getElementById("myButton").addEventListener("click", function() {
initMarker();
myTimer();
});
}
function initMarker() {
var t1 = 1;
marker1 = new google.maps.Marker({map: map,position: new google.maps.LatLng(37.55020520861464,126.98140242753904)});
marker2 = new google.maps.Marker({map: map,position: new google.maps.LatLng(37.558816, 126.908212)});
marker3 = new google.maps.Marker({map: map,position: new google.maps.LatLng(37.580107, 127.056797)});
marker4 = new google.maps.Marker({map: map,position: new google.maps.LatLng(37.446290, 126.862625)});
marker5 = new google.maps.Marker({map: map,position: new google.maps.LatLng(37.435041, 126.999528)});
marker6 = new google.maps.Marker({map: map,position: new google.maps.LatLng(37.522926, 126.853862)});
marker1.addListener('click', function() {
var triangleCoords = [
{lat: 37.550, lng: 123.9814},
{lat: 18.466, lng: -66.118},
{lat: 32.321, lng: -64.757},
{lat: 25.774, lng: -80.190}
];
var triangle1 = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: 'FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
if (t1 == 1) {
triangle1.setMap(map);
t1 = 2;
}
else {
triangle1.setMap(null);
t1 = 1;
}
});
}
</script>
<div><button id="myButton">Start</button></div>
<div id="timer"></div>
<p id="explain"></p>
<script src='https://maps.googleapis.com/maps/api/js?v=3.exp'
async defer ></script>
</body>
Try moving the new polygon inside the if statement. I think, when ever you evoke that function it makes a new instance of triangle1, that's why when you try to remove polygon it deletes the new instance of "var triangle1" (which wasn't drawn to to map yet) rather than the one on the map. (sorry about the English)
marker1.addListener('click', function() {
var triangleCoords = [
{lat: 37.550, lng: 123.9814},
{lat: 18.466, lng: -66.118},
{lat: 32.321, lng: -64.757},
{lat: 25.774, lng: -80.190}
];
if (t1 == 1) {
var triangle1 = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: 'FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
triangle1.setMap(map);
t1 = 2;
}
else {
triangle1.setMap(null);
t1 = 1;
}
});
One option (from Removing Rectangle from Map, slightly modified...
define the triangle1 variable outside the scope of the click listener
check if the triangle1 object exists and has a .setMap method.
if it does, set it's map property to null (the polygon is currently displayed), hide it, and set it to null.
if it doesn't exist, or doesn't have a .setMap method, create the marker.
var map;
function initMap() {
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(37.55020520861464, 126.98140242753904),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), myOptions);
document.getElementById("myButton").addEventListener("click", function() {
initMarker();
});
}
function initMarker() {
marker1 = new google.maps.Marker({
map: map,
title: "marker 1",
position: new google.maps.LatLng(37.55020520861464, 126.98140242753904)
});
var triangle1;
marker1.addListener('click', function(evt) {
if (triangle1 && triangle1.setMap) {
triangle1.setMap(null);
triangle1 = null;
} else {
var triangleCoords = [{
lat: 37.550,
lng: 123.9814
}, {
lat: 18.466,
lng: -66.118
}, {
lat: 32.321,
lng: -64.757
}, {
lat: 25.774,
lng: -80.190
}];
triangle1 = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: 'FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map
});
}
});
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div>
<button id="myButton">Start</button>
</div>
<div id="timer"></div>
<p id="explain"></p>
<div id="map"></div>

Place Google Map Marker icon using javascript taking images from Image asset in iOS

Hi I am trying to set marker icon in Google Map using javascript. My image is in Images.xcassets. Right now I am doing this to set icon. But its not working for me. What I am doing is this:
setMarkerWithIcon('/Images/MapScreen/MapviewIcon/MapviewIcon');
function initialize(latitude, longitude, maxzoom) {
var styles = [{
elementType: "labels",
stylers: [
{ visibility: "off" }
]
}];
var styledMap = new google.maps.StyledMapType(styles,
{name: "Styled Map"});
var mapOptions = {
zoom: initialZoomLevel,
center: new google.maps.LatLng(latitude + LatLngDeltas[ randomIntFromInterval(0, LatLngDeltas.length) ],
longitude + LatLngDeltas[ randomIntFromInterval(0, LatLngDeltas.length) ] ),
disableDefaultUI: true,
disableDoubleClickZoom: false,
minZoom: initialZoomLevel,
maxZoom: maxzoom,
scrollwheel: false,
scaleControl: false,
rotateControl:true,
rotateControlOptions: {
position: google.maps.ControlPosition.LEFT_CENTER
},
mapTypeControl: false,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
}
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
map.mapTypes.set('map_style', styledMap);
map.setMapTypeId('map_style');
google.maps.event.addListener(map, 'click', function(event) {
addMarker(map, event.latLng);
});
}
function addMarker(mapObject, location) {
deleteMarkers();
var marker = new google.maps.Marker({
position: location,
draggable:true,
animation: google.maps.Animation.DROP,
map: mapObject,
icon:markerPath
});
setTimeout(function() {infowindow.open(mapObject,marker);}, 500);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(mapObject,marker);
});
markers.push(marker);
}
function setMarkerWithIcon(myIcon) {
markerPath = myIcon;
}
Any help is highly appreciated.

Google map shows gray box instead map

I searched a lot for solve this issue, but i can't resolve this issue. map show gray, see picture:
I test this event trigger:
google.maps.event.trigger(draw_map, "resize")
and in style
div {
overflow: hidden;
}
But, again doesn't work! This is initialize code for google map:
var draw_map = '';
var drawingManager;
var selectedShape;
var resc;
var rest;
var resx;
var resy;
jQuery(document).ready(function(){
initialize_draw_map();
});
function initialize_draw_map() {
if (draw_map != '')
return false;
var myLatlng = new google.maps.LatLng(90, 90);
var myOptions = {
zoom: 11,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
draw_map = new google.maps.Map(document.getElementById("map_canvas_draw_map"), myOptions);
var polyOptions = {
strokeWeight: 0,
fillOpacity: 0.30,
editable: true,
fillColor: '#1E90FF',
zIndex: 1
};
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.RECTANGLE,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_LEFT,
drawingModes: [google.maps.drawing.OverlayType.CIRCLE, google.maps.drawing.OverlayType.RECTANGLE,
google.maps.drawing.OverlayType.POLYGON, google.maps.drawing.OverlayType.POLYLINE
]
},
polygonOptions: polyOptions,
rectangleOptions: polyOptions,
circleOptions: polyOptions,
map: draw_map
});
}
Loading libraries:
http://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places,drawing
in this page my another google map work as well.
This point var myLatlng = new google.maps.LatLng(90, 90); is at the North Pole. The tiles there are grey.
fiddle with your code
If I change the map options to a more reasonable place (in the US where there are non-grey tiles):
var myLatlng = new google.maps.LatLng(42, -90);
var myOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
I no longer get the "grey" map: working fiddle
working code snippet:
var draw_map = '';
var drawingManager;
var selectedShape;
var resc;
var rest;
var resx;
var resy;
jQuery(document).ready(function() {
initialize_draw_map();
});
function initialize_draw_map() {
if (draw_map != '')
return false;
var myLatlng = new google.maps.LatLng(42, -90);
var myOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
draw_map = new google.maps.Map(document.getElementById("map_canvas_draw_map"), myOptions);
var polyOptions = {
strokeWeight: 0,
fillOpacity: 0.30,
editable: true,
fillColor: '#1E90FF',
zIndex: 1
};
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.RECTANGLE,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_LEFT,
drawingModes: [google.maps.drawing.OverlayType.CIRCLE, google.maps.drawing.OverlayType.RECTANGLE,
google.maps.drawing.OverlayType.POLYGON, google.maps.drawing.OverlayType.POLYLINE
]
},
polygonOptions: polyOptions,
rectangleOptions: polyOptions,
circleOptions: polyOptions,
map: draw_map
});
}
html,
body,
#map_canvas_draw_map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,places,drawing&ext=.js"></script>
<div id="map_canvas_draw_map" style="border: 2px solid #3872ac;"></div>
Usually a grey map is caused by the wrong Google Maps API or deprecated function calls.
However it could also be the API KEY. Make sure you have a valid one.

Markers are not visible in google map

I'm trying to display google map with markers and circles. The map and the circle is displaying correctly but the marker are not visible on the map.
Please suggest what changes i should make in my code.
<div id="mapview" style="width: 100%; height: 700px;">
</div>
<script>
var map;
var info_window;
function initialize() {
var mapOptions = {
zoom: 11,
center: new google.maps.LatLng(51.561918, -0.31237799999996696),
mapTypeId: google.maps.MapTypeId.ROADMAP, scrollwheel: false
};
map = new google.maps.Map(document.getElementById('mapview'), mapOptions);
var image = '../Image/salemarker.png';
var user = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(51.561918, -0.31237799999996696),
animation: google.maps.Animation.DROP, icon: image
});
var circle = new google.maps.Circle({
map: map,
radius: 1609.344, // 10 miles in metres
strokeColor: '#08355A;',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#fffff',
fillOpacity: 0.2,
});
info_window = new google.maps.InfoWindow({
content: 'loading'
});
user.setMap(null);
function addMarkersc() {
createLocationOnMap('4 bed semi detached For sale', new google.maps.LatLng(51.5661728, 51.5661728), '<p>48, The fairway, wembley, HA..</p>');
}
addMarkersc();
circle.bindTo('center', user, 'position');
map.fitBounds(circle.getBounds());
}
google.maps.event.addDomListener(window, 'load', initialize);
var image1 = '../Image/salemarker.png';
function createLocationOnMap(titulo, posicao, conteudo) {
var m = new google.maps.Marker({
map: map,
title: titulo,
icon: image1,
position: posicao,
html: conteudo
});
google.maps.event.addListener(m, 'mouseover', function () {
info_window.setContent(this.html);
info_window.open(map, this);
});
}
</script>
Your marker is out of view. It is at 51.5661728,51.5661728:
createLocationOnMap('4 bed semi detached For sale', new google.maps.LatLng(51.5661728,51.5661728), '<p>48, The fairway, wembley, HA..</p>');}
Your map is centered at 51.561918,-0.31237799999996696
var mapOptions = {
zoom: 11,
center: new google.maps.LatLng(51.561918,-0.31237799999996696),
mapTypeId: google.maps.MapTypeId.ROADMAP,scrollwheel: false
};
working fiddle
You can try this
function InitializeMap1() {
geocoderMap = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(48.856614, 2.352222);
var myOptions =
{
zoom: 12,
minZoom: 12, // panControl: false, zoomControl: false, scaleControl: false, streetViewControl: true, //
center: latlng,
streetViewControl: false,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
zoomControl: true
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
var arrayMain = [];
var markerLatLng = new google.maps.LatLng(48.856614, 2.352222);
var marker = new google.maps.Marker({
map: map,
position: markerLatLng,
center: markerLatLng
});
arrayMain.push(marker);
}
Try like this:
<div id="mapview" style="width: 100%; height: 700px">
<script>
var map;
var info_window;
function addMarkersc() {
var titulo = '4 bed semi detached For sale';
var posicao = new google.maps.LatLng(51.5661728,51.5661728);
var conteudo = '<p>48, The fairway, wembley, HA..</p>';
var image = '../Image/salemarker.png';
var m = new google.maps.Marker({
map: map,
title: titulo,
icon: image,
position: posicao,
html: conteudo
});
google.maps.event.addListener(m, 'mouseover', function () {
info_window.setContent(this.html);
info_window.open(map, this);
});
}
function initialize() {
var mapOptions = {
zoom: 11,
center: new google.maps.LatLng(51.561918,-0.31237799999996696),
mapTypeId: google.maps.MapTypeId.ROADMAP,scrollwheel: false
};
map = new google.maps.Map(document.getElementById('mapview'),mapOptions);
var image = '../Image/salemarker.png';
var user = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(51.561918,-0.31237799999996696),
animation: google.maps.Animation.DROP,
icon: image
});
var circle = new google.maps.Circle({
map: map,
radius: 1609.344, // 10 miles in metres
strokeColor: '#08355A;',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#fffff',
fillOpacity: 0.2,
});
info_window = new google.maps.InfoWindow({
content: 'loading'
});
user.setMap(null);
circle.bindTo('center', user, 'position');
map.fitBounds(circle.getBounds());
addMarkersc();
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

Categories

Resources