Allow markers only within an area

by Génesis García Morilla

HTML

<script src="https://maps.google.com/maps/api/js"></script>
<div id="map"></div>

CSS

* {
  padding: 0;
  margin: 0;
}

#map {
  height: 100vh;
}

JavaScript

// Styles
const ORANGE = '#FFB000'
const DARK = [{
  featureType: 'all',
  stylers: [
    { saturation: -100 },
    { lightness: -30 }
  ]
}]

// Map
const map = new google.maps.Map(document.querySelector('#map'), {
  center: { lat: -34.6037, lng: -58.3816 }, // Buenos Aires coordinates
  zoom: 12,
  styles: DARK
})

// Buenos Aires area
const buenos_aires = [
  { lat: -34.6915, lng: -58.4177 },
  { lat: -34.5714, lng: -58.4225 },
  { lat: -34.5715, lng: -58.3708 },
  { lat: -34.6354, lng: -58.3284 },
  { lat: -34.6677, lng: -58.3431 },
  { lat: -34.6915, lng: -58.4177 }
]

const buenos_aires_poli = new google.maps.Polygon({
  paths: buenos_aires,
  strokeColor: ORANGE,
  strokeOpacity: 0.8,
  strokeWeight: 2,
  fillColor: ORANGE,
  fillOpacity: 0.35,
  saturation: 200,
  map
})

// Marker
let marker

google.maps.event.addListener(buenos_aires_poli, 'click', e => {
  if (marker) marker.setMap(null)

  marker = new google.maps.Marker({
    position: e.latLng,
    map,
    draggable: true
  })
  
  google.maps.event.addListener(marker, 'dragend', e => {
    if (!google.maps.geometry.poly.containsLocation(e.latLng, buenos_aires_poli)) {
      marker.setMap(null)
      alert('Marker outside of Buenos Aires. Please keep the marker within the Buenos Aires area.')
    }
  })
})