Polygon not show in Google Maps - javascript

I obtain the polygon coordinates through an AJAX request and I pass all the coordinates to an associative array.
The problem is, when I create the Polygon this don't show, but if I create it with the coordinates example this show.
This is the code:
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.7281512, lng: -58.262616},
zoom: 10
});
var coords = new Array();
$.ajax({
type: 'GET',
url: 'http://nominatim.openstreetmap.org/reverse?format=json&osm_type=R&osm_id=2532299&polygon_geojson=1',
data: { get_param: 'value' },
success: function (data) {
$.each(data.geojson.coordinates[0], function( index, value ) {
if(typeof value[0] !== 'undefined' && typeof value[1] !== 'undefined') {
coords.push({lat: value[0], lng: value[1]});
}
});
}
});
var zone = new google.maps.Polygon({
paths: coords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
zone.setMap(map);
}
If I make the same, with the google example, this works fine. I don't know why my associative array don't work.
Code of the example:
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.7281512, lng: -58.262616},
zoom: 10
});
var triangleCoords = [
{lat: -34.817177, lng: -58.500948},
{lat: -34.688414, lng: -58.500948},
{lat: -34.688414, lng: -58.336764},
{lat: -34.817177, lng: -58.336764},
{lat: -34.817177, lng: -58.500948}
];
var zone = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
zone.setMap(map);
}

You have two issues with the posted code.
Your $.ajax call is asynchronous, so the data isn't available when you try to populate the paths attribute of the polygon. You need to use the data in the callback function when/where it is available.
You have the latitude and longitude reversed in the path of the polygon.
$.ajax({
type: 'GET',
url: 'http://nominatim.openstreetmap.org/reverse?format=json&osm_type=R&osm_id=2532299&polygon_geojson=1',
data: {
get_param: 'value'
},
success: function(data) {
var zone = new google.maps.Polygon({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map
});
$.each(data.geojson.coordinates[0], function(index, value) {
if (typeof value[0] !== 'undefined' && typeof value[1] !== 'undefined') {
coords.push({
lat: value[1],
lng: value[0]
});
}
zone.setPath(coords);
});
}
})
proof of concept fiddle
code snippet:
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.7281512,
lng: -58.262616
},
zoom: 10
});
var coords = new Array();
$.ajax({
type: 'GET',
url: 'https://nominatim.openstreetmap.org/reverse?format=json&osm_type=R&osm_id=2532299&polygon_geojson=1',
data: {
get_param: 'value'
},
success: function(data) {
var zone = new google.maps.Polygon({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map
});
$.each(data.geojson.coordinates[0], function(index, value) {
if (typeof value[0] !== 'undefined' && typeof value[1] !== 'undefined') {
coords.push({
lat: value[1],
lng: value[0]
});
}
zone.setPath(coords);
});
}
})
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

Related

isLocationOnEdge() to split the route

I'm a web developer is brazilian, I am doing a service to the routing system for my company, however I am having difficulties in understanding the library's geometry, I would like to know if there is any way for me to know where the route is drawn is Inside of the polygon 1, 2, 3, or 4). This is it for me to make a division of the route, and to trace up to 4 connections. It has a picture of the bottom with the one I already have, along with the code.
function initMap() {
var map = new google.maps.Map(document.getElementById("map"));
function renderDirections(result) {
var directionsRenderer = new google.maps.DirectionsRenderer;
directionsRenderer.setMap(map);
directionsRenderer.setDirections(result);
}
var triangle1 = [
{lat: -23.0829, lng: -46.57676},
{lat: -23.61616, lng: -46.57483},
{lat: -23.60694, lng: -47.54864}
];
var Triangle1 = new google.maps.Polygon({
paths: triangle1,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#00FF00',
fillOpacity: 0.35
});
Triangle1.setMap(map);
var triangle2 = [
{lat: -23.0829, lng: -46.57676},
{lat: -23.61616, lng: -46.57483},
{lat: -23.61131, lng: -45.67469}
];
var Triangle2 = new google.maps.Polygon({
paths: triangle2,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#4169E1',
fillOpacity: 0.35
});
Triangle2.setMap(map);
var triangle3 = [
{lat: -23.61131, lng: -45.67469},
{lat: -23.61616, lng: -46.57483},
{lat: -24.07554, lng: -46.57185}
];
var Triangle3 = new google.maps.Polygon({
paths: triangle3,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FFA500',
fillOpacity: 0.35
});
Triangle3.setMap(map);
var triangle4 = [
{lat: -24.07554, lng: -46.57185},
{lat: -23.60694, lng: -47.54864},
{lat: -23.61616, lng: -46.57483}
];
var Triangle4 = new google.maps.Polygon({
paths: triangle4,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FFFF00',
fillOpacity: 0.35
});
Triangle4.setMap(map);
var directionsService = new google.maps.DirectionsService;
function requestDirections() {
directionsService.route({
origin: "Rua pedro jose lorenzini",
destination: "Rua pedro jose lorenzini",
waypoints: waypts,
optimizeWaypoints: true,
provideRouteAlternatives: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result) {
renderDirections(result);
if(google.maps.geometry.poly.containsLocation(result, Triangle1) == true) {
alert("yes");
}
});
}
requestDirections(waypts);
requestDirections(waypts2);
}
Google Maps
I got it
First I retrieved the coordinates of the addresses that would be part of the route, I placed each one inside its respective fields, after that I put the function to check if that coordinate belonged to the polygon, returning the value true it was placed inside the route array
function(result) {
for(var i = 0; i < 24; i++){
if($("#latLgn_"+i).val() != "" || $("#latLgn"+i).val() != undefined){
temp = $("#latLgn"+i).val()
temp = temp.split(",")
temp[0] = temp[0].replace("(","")
temp[1] = temp[1].replace(")","")
temp[0] = Number(temp[0])
temp [1] = Number(temp[1])
var point = new google.maps.LatLng({lat: temp[0], lng: temp[1]})
if(google.maps.geometry.poly.containsLocation(point, Triangle1) == true) {
route.push($("#latLgn"+i).val());
}else{console.log("Not found")}
}
}
renderDirections(result);
}

getBounds().contains returning false

I want the marker to be detected and display a value that is assigned to a rectangle. Through research, I found this, but it is not applicable in my case as I only need a latlong point. I have found something similar to what I want and tried it out, which is here
But it does not seem to work in my case.
I have a rectangle below:
var rectangle1 = new google.maps.Rectangle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
bounds: {
north: -37.822802,
south: -37.822260,
east: 145.036010,
west: 145.035324
}
});
And I tried to insert a point, which is -37.822545, 145.035526, and this point is within the rectangle, and it is supposed to return true but it wasn't.
Here is my JSfiddle
Looks like the LatLngLiteralBounds input for google.maps.Rectangle is broken. It creates a rectangle with north and south reversed. With your original rectangle (north: -37.822802, south: -37.822260), I get:
NE1:-37.822802,145.03601 (north=-37.822802, incorrect)
SW1:-37.82226,145.035324 (south=-37.82226, incorrect)
Whereas if I create the rectangle with a google.maps.LatLngBounds object, I get:
NE2:-37.82226,145.03601 (north=-37.82226, correct)
SW2:-37.822802,145.035324 (south=-37.822802, correct)
proof of concept fiddle
(blue markers are NE/SW of rectangle2, red markers are NE/SW of rectangle1.)
someone should create an issue in the issue tracker
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 19,
center: {
lat: -37.82280243352756,
lng: 145.0353240966797
},
mapTypeId: 'terrain'
});
var rectangle1 = new google.maps.Rectangle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
bounds: {
north: -37.822802,
south: -37.822260,
east: 145.036010,
west: 145.035324
}
});
var rectangle2 = new google.maps.Rectangle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
bounds: new google.maps.LatLngBounds(
new google.maps.LatLng(-37.822802, 145.035324), // SW
new google.maps.LatLng(-37.822260, 145.036010)) // NE
});
var marker = new google.maps.Marker({
map: map,
position: {
lat: -37.822545,
lng: 145.035526
},
title: "-37.822545, 145.035526"
});
var NEmark1 = new google.maps.Marker({
map: map,
position: rectangle1.getBounds().getNorthEast(),
title: "NE1:" + rectangle1.getBounds().getNorthEast().toUrlValue()
});
var SWmark1 = new google.maps.Marker({
map: map,
position: rectangle1.getBounds().getSouthWest(),
title: "SW1:" + rectangle1.getBounds().getSouthWest().toUrlValue()
});
var NEmark2 = new google.maps.Marker({
map: map,
position: rectangle2.getBounds().getNorthEast(),
title: "NE2:" + rectangle2.getBounds().getNorthEast().toUrlValue(),
icon: "http://maps.google.com/mapfiles/ms/micons/blue.png"
});
var SWmark2 = new google.maps.Marker({
map: map,
position: rectangle2.getBounds().getSouthWest(),
title: "SW2:" + rectangle2.getBounds().getSouthWest().toUrlValue(),
icon: "http://maps.google.com/mapfiles/ms/micons/blue.png"
});
map.fitBounds(rectangle1.getBounds());
console.log(rectangle1.getBounds().toUrlValue());
console.log("NE1:" + rectangle1.getBounds().getNorthEast().toUrlValue());
console.log("SW1:" + rectangle1.getBounds().getSouthWest().toUrlValue());
document.getElementById('contains').innerHTML = "rectangle1 bounds.contains=" + rectangle1.getBounds().contains({
lat: -37.822545,
lng: 145.035526
});
console.log(marker.getPosition().toUrlValue());
console.log(rectangle2.getBounds().toUrlValue());
console.log("NE2:" + rectangle2.getBounds().getNorthEast().toUrlValue());
console.log("SW2:" + rectangle2.getBounds().getSouthWest().toUrlValue());
console.log(rectangle2.getBounds().contains({
lat: -37.822545,
lng: 145.035526
}));
document.getElementById('contains').innerHTML += " rectangle2 bounds.contains=" + rectangle2.getBounds().contains({
lat: -37.822545,
lng: 145.035526
});
console.log(rectangle2.getBounds().contains(marker.getPosition()));
}
html,
body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
#map {
height: 95%;
width: 100%;
}
<div id="contains"></div>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
I think you just mixed up your north and south parameters. (A larger negative latitude number is further south than a smaller one)
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 19,
center: {
lat: -37.82280243352756,
lng: 145.0353240966797
},
mapTypeId: 'terrain'
});
var rectangle1 = new google.maps.Rectangle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
bounds: {
south: -37.822802, // This is further south ...
north: -37.822260, // than this
east: 145.036010,
west: 145.035324
}
});
alert(rectangle1.getBounds());
alert(rectangle1.getBounds().contains({lat:-37.822545, lng:145.035526}));
}
With north and south switched like this, the js-fiddle returns true.

How to get Notification if Marker gets inside a polygon

Im trying to get a Notification if My marker gets into any of the polygons inside the map. However, can't seem to find a way to do it correctly, this is my code so far:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="signin.js"> </script>
<script src="https://www.gstatic.com/firebasejs/4.10.1/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyAjp8cvAcEYCwzuCyTQORL3Z1iQPdQMg_8",
authDomain: "just-don-t.firebaseapp.com",
databaseURL: "https://just-don-t.firebaseio.com",
projectId: "just-don-t",
storageBucket: "just-don-t.appspot.com",
messagingSenderId: "925350346315"
};
firebase.initializeApp(config);
</script>
<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.19.0.min.js"> </script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAjp8cvAcEYCwzuCyTQORL3Z1iQPdQMg_8&libraries=drawing&callback=initMap" async defer> </script>
<header><h1><center><b>WELCOME TO THE JUST DON'T APP</b> </center></h1></header>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<style >
html, body, #map {
height: 100%;
margin: 0;
padding: 0;
}
body {font-family: Arial, Helvetica, sans-serif;}
[...] Here is just visual parts of the app such as buttons and such, it should not affect the rest of the app [...]
<div id="map"></div>
<script>
var lineCoords = [];
var pubnub = new PubNub({
publishKey: 'pub-c-22289088-791b-4f24-900a-84dc41c860bf',
subscribeKey: 'sub-c-e781e56c-23f5-11e8-a8f3-22fca5d72012'
});
window.lat = 55.845890;
window.lng = -4.423741;
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(updatePosition);
}
return null;
};
function updatePosition(position) {
if (position) {
window.lat = position.coords.latitude;
window.lng = position.coords.longitude;
}
}
setInterval(function(){updatePosition(getLocation());}, 10000);
function currentLocation() {
return {lat:window.lat, lng:window.lng};
};
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: lat, lng: lng},
zoom: 17
});
var infoWindow = new google.maps.InfoWindow({
map: map
});
var pleasantAreaCoords = [
{lat: 55.84478883022466, lng:-4.423067882047013},
{lat: 55.84485326696093, lng: -4.422505549698727},
{lat: 55.84538931148452, lng: -4.4228536960804},
{lat: 55.84525930830721, lng: -4.423344253807979},
{lat: 55.84478883022466, lng: -4.423067882047013}
];
var pleasant = new google.maps.Polygon({
paths: pleasantAreaCoords,
strokeColor: '#E9F52C',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#E9F52C',
fillOpacity: 0.35
});
pleasant.setMap(map);
var unsafeCoords = [
{lat: 55.84582542929267, lng:-4.423879981040955 },
{lat: 55.845723031335204, lng: -4.424362778663635},
{lat: 55.84565677368958, lng:-4.424352049827576},
{lat: 55.845723031335204, lng:-4.4238585233688354},
{lat: 55.8458284409932, lng: -4.423881322145462}
]
var unsafe_area = new google.maps.Polygon({
paths: unsafeCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
unsafe_area.setMap(map);
var unpleasantAreacoords = [
{lat: 55.84580133567989,lng:-4.424523711204529},
{lat: 55.84583747609345,lng: -4.424319863319397},
{lat: 55.84653618415134,lng: -4.424673914909363},
{lat: 55.8465000443874,lng: -4.425221085548401},
{lat: 55.84580160878137,lng: -4.4245168063742994}
];
var unpleasant = new google.maps.Polygon({
paths: unpleasantAreacoords,
strokeColor: '#F5942C',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#F5942C',
fillOpacity: 0.35
});
unpleasant.setMap(map);
var commercialZoneCoords = [
{lat: 55.846999974806145,lng: -4.423676133155823},
{lat: 55.84714453180107,lng: -4.421852231025696},
{lat: 55.84583747609345,lng: -4.421680569648743},
{lat: 55.84553630495364,lng: -4.423472285270691}
];
var commercialZone = new google.maps.Polygon({
paths: commercialZoneCoords,
strokeColor: '#3CB2F1',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#3CB2F1',
fillOpacity: 0.35
});
commercialZone.setMap(map);
var mainStreetCoords =[
{lat: 55.84504840275506,lng: -4.426873326301575},
{lat: 55.84528331939289,lng: -4.4235581159591675},
{lat: 55.84553028150705,lng: -4.423697590827942},
{lat: 55.8452652489327,lng: -4.426959156990051}
];
var mainStreet = new google.maps.Polygon({ paths: mainStreetCoords,
strokeColor: '#E63CF1',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#E63CF1',
fillOpacity: 0.35
});
mainStreet.setMap(map);
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var initialize = function() {
map = new google.maps.Map(document.getElementById('map-canvas'), {center:{lat:lat,lng:lng},zoom:12});
mark = new google.maps.Marker({position:{lat:lat, lng:lng}, map:map});
};
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
window.initialize = initialize;
var Paisley = pos;
var mark = new google.maps.Marker({
position:{lat:lat, lng:lng},
map:map,
});
var redraw = function(payload) {
lat = payload.message.lat;
lng = payload.message.lng;
mark.setPosition({lat:lat, lng:lng, alt:0});
lineCoords.push(new google.maps.LatLng(lat, lng));
var lineCoordinatesPath = new google.maps.Polyline({
path: lineCoords,
geodesic: true,
strokeColor: '#2E10FF'
});
lineCoordinatesPath.setMap(map);
};
point = position;
var pnChannel = "map-channel";
var pubnub = new PubNub({
publishKey: 'pub-c-22289088-791b-4f24-900a-84dc41c860bf',
subscribeKey: 'sub-c-e781e56c-23f5-11e8-a8f3-22fca5d72012'
});
pubnub.subscribe({channels: [pnChannel]});
pubnub.addListener({message:redraw});
map.setCenter({lat:lat, lng:lng, alt:0});
setInterval(function() {
pubnub.publish({channel:pnChannel, message:currentLocation()});
}, 100);
}, function () {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
}
</script>
</body>
</html>
And here is the code Im trying to implement to detect and notify if the marker gets inside the polygon (for this example I am using
point = Marker
if(google.maps.containsLocation(point, mainStreetCoords) == true) {
alert("You are at the Main street");
}
If I get it to work will update this but would appreciate if someone could explain me how to get it to work.
according to Google map api document
// This example requires the Geometry library. Include the libraries=geometry
// parameter when you first load the API. For example:
// <script src=".../maps/api/js?key=YOUR_API_KEY&libraries=geometry">
google.maps.geometry.poly.containsLocation(e.latLng, bermudaTriangle)
the first variable would be like this var point = new google.maps.LatLng(x, y);
but not a marker
so I tried your code (but mine google map api ;) )
add a click event and test, it works
here's working code
commercialZone.addListener('click', function(e) {
var marker = new google.maps.Marker({
position: e.latLng,
map: map,
icon: {
path: google.maps.SymbolPath.CIRCLE,
fillColor: "red",
fillOpacity: .2,
strokeColor: 'white',
strokeWeight: .5,
scale: 10
}
});
if(google.maps.geometry.poly.containsLocation(marker.position, commercialZone) == true) {
alert("You are at the Main street");
}
});
if you click on commercialZone (blue one), alert will be triggered
you can do what you want base on this
hope this helps

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>

Add new polygon below everything in Google Maps API

I have a Google.Map object with a set of polygons and polylines already being displayed on that.
I want to add a new google.maps.Polygon object that should be displayed below all elements (more or less like a "background" polygon).
I tried to add it with an absurd low zIndex value (-999999), but it still is displayed above all other elements.
This is what I have done so far:
whiteBackground = new google.maps.Polygon({
path: [ {lat:40.1, lng:-97.1},
{lat:40.1, lng:-89.8},
{lat:44.5, lng:-89.8},
{lat:44.5, lng:-97.1} ],
strokeColor: "#FF0000",
fillColor: "#FFFFFF",
strokeOpacity: 1.0,
strokeWeight: 1.5,
fillOpacity: 1.0,
zIndex: -999999
});
// add to map and to list
whiteBackground.setMap(my_map);
Is there a way to force new polygon whiteBackground to have the smallest zIndex value in the Google.Map in which it is going to be add?
Or there is an way to iterate over all current elements in a Google.Map object?
It works if you set the zIndex properties of all the polygons.
proof of concept fiddle (moves smaller polygon above/below larger polygon on click of the button)
code snippet:
// This example creates a simple polygon representing the Bermuda Triangle and a small polygon that starts above it, toggles above/below by clicking the button (large polygon has zIndex=0; small polygon is +/-1.
var map;
var infoWindow;
var poly2;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {
lat: 24.886,
lng: -70.268
},
mapTypeId: google.maps.MapTypeId.TERRAIN
});
// Define the LatLng coordinates for the polygon.
var triangleCoords = [{
lat: 25.774,
lng: -80.190
}, {
lat: 18.466,
lng: -66.118
}, {
lat: 32.321,
lng: -64.757
}];
// Construct the polygon.
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FF0000',
fillOpacity: 0.35,
zIndex: 0
});
bermudaTriangle.setMap(map);
var poly2Coords = [{
lat: 26.78484736105119,
lng: -72.24609375
}, {
lat: 27.059125784374068,
lng: -68.8623046875
}, {
lat: 23.926013339487024,
lng: -71.806640625
}];
poly2 = new google.maps.Polygon({
paths: poly2Coords,
strokeColor: '#0000FF',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FF0000',
fillOpacity: 0.35,
zIndex: 1
});
poly2.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initMap);
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="info"></div>
<input id="btn" type="button" value="click" onclick="if (poly2.get('zIndex') > 0) poly2.setOptions({zIndex:-1}); else poly2.setOptions({zIndex:1});" />
<div id="map"></div>

Categories

Resources