How to get Notification if Marker gets inside a polygon - javascript

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

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);
}

How to remove multiple Circle for google map

I am trying to remove all the 4 circle from google map with a click of a button, but currently I can only remove one circle. Could anyone let me know how I can remove the multiple circle at once with a click of a button. Sorry I am new to this. Thanks in advance.
My code:
<input onclick="removecircle();" type=button value="Remove line">
<input onclick="addcircle();" type=button value="Restore line">
<div id="map"></div>
<script>
var cityCircle;
var citymap = {
chicago: {
center: {lat: 41.878, lng: -87.629},
population: 2714856
},
newyork: {
center: {lat: 40.714, lng: -74.005},
population: 8405837
},
losangeles: {
center: {lat: 34.052, lng: -118.243},
population: 3857799
},
vancouver: {
center: {lat: 49.25, lng: -123.1},
population: 603502
}
};
function initMap() {
// Create the map.
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: 37.090, lng: -95.712},
mapTypeId: 'terrain'
});
// 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) {
// Add the circle for this city to the map.
cityCircle = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: citymap[city].center,
radius: Math.sqrt(citymap[city].population) * 100
});
}
}
function addcircle(){
cityCircle.setMap(map);
}
function removecircle(){
cityCircle.setMap(null);
}
Image 1
Image 2
You need to keep references to the circles (and the map) in the global scope (where they will be accessible from HTML click listener functions). Then process through all the circles to either add or remove them from the map.
var circles = [];
var map;
function initMap() {
// Create the map.
map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: 37.090,
lng: -95.712
},
mapTypeId: 'terrain'
});
// 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) {
// Add the circle for this city to the map.
var cityCircle = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: citymap[city].center,
radius: Math.sqrt(citymap[city].population) * 100
});
// keep reference to the circle
circles.push(cityCircle);
}
}
function addcircle() {
for (var i = 0; i < circles.length; i++) {
circles[i].setMap(map);
}
}
function removecircle() {
for (var i = 0; i < circles.length; i++) {
circles[i].setMap(null);
}
}
proof of concept fiddle
code snippet:
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
width: 100%;
}
<input onclick="removecircle();" type=button value="Remove circles">
<input onclick="addcircle();" type=button value="Restore circles">
<script src="https://maps.googleapis.com/maps/api/js" type="text/javascript"></script>
<div id="map"></div>
<script>
var circles = [];
var map;
function initMap() {
// Create the map.
map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: 37.090,
lng: -95.712
},
mapTypeId: 'terrain'
});
// 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) {
// Add the circle for this city to the map.
var cityCircle = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: citymap[city].center,
radius: Math.sqrt(citymap[city].population) * 100
});
circles.push(cityCircle);
}
}
function addcircle() {
for (var i = 0; i < circles.length; i++) {
circles[i].setMap(map);
}
}
function removecircle() {
for (var i = 0; i < circles.length; i++) {
circles[i].setMap(null);
}
}
google.maps.event.addDomListener(window, 'load', initMap);
var cityCircle;
var citymap = {
chicago: {
center: {
lat: 41.878,
lng: -87.629
},
population: 2714856
},
newyork: {
center: {
lat: 40.714,
lng: -74.005
},
population: 8405837
},
losangeles: {
center: {
lat: 34.052,
lng: -118.243
},
population: 3857799
},
vancouver: {
center: {
lat: 49.25,
lng: -123.1
},
population: 603502
}
};
</script>

Polygon not show in Google Maps

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>

Javascript - Trigger Click on Page Load

I've made a website with the Google Maps API. If users click in a polygon a message appears. It works on click, so the user has to click in or outside the Polygon area, but I would like to make it on page load, based on the users current position.
Is it possible to trigger the function below on page load?
google.maps.event.addListener(map, 'click', function (event) {
if (boundaryPolygon!=null && boundaryPolygon.Contains(event.latLng)) {
document.getElementById('result').innerHTML = 'You live in this area.';
} else {
//alert(event.latLng + " Du bist ein Ossi!");
document.getElementById('result').innerHTML = 'You live outside this area.';
}
});
}
You can trigger a click event on the map like this (where the latLng property is the location of the click):
google.maps.event.trigger(map, 'click', {
latLng: new google.maps.LatLng(24.886, -70.268)
});
proof of concept fiddle
code snippet:
// polygon example from: https://developers.google.com/maps/documentation/javascript/examples/polygon-simple
// This example creates a simple polygon representing the Bermuda Triangle.
function initMap() {
var 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's path.
var triangleCoords = [{
lat: 25.774,
lng: -80.190
}, {
lat: 18.466,
lng: -66.118
}, {
lat: 32.321,
lng: -64.757
}, {
lat: 25.774,
lng: -80.190
}];
// Construct the polygon.
var boundaryPolygon = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
clickable: false
});
boundaryPolygon.setMap(map);
google.maps.event.addListener(map, 'click', function(event) {
if (boundaryPolygon != null && google.maps.geometry.poly.containsLocation(event.latLng, boundaryPolygon)) {
document.getElementById('result').innerHTML = 'You live in this area.';
} else {
document.getElementById('result').innerHTML = 'You live outside this area.';
}
});
google.maps.event.trigger(map, 'click', {
latLng: new google.maps.LatLng(24.886, -70.268)
});
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<div id="result"></div>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?libraries=geometry&callback=initMap">
</script>

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>

Categories

Resources