Geolocation

by Amir Sharifian

HTML

<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?key=AIzaSyA7K6UAq99_g2rMmJs39l7BmmBTf6HwSjs&callback=initMap&language=fa&region=IR">
</script>?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>

CSS

html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 100%;
}

JavaScript

// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see the error "The Geolocation service
// failed.", it means you probably did not give permission for the browser to
// locate you.

function initMap() {
var locations = [
      ['Bondi Beach', 36.32677, 59.53967, 4],
      ['Coogee Beach', 36.32698, 59.54054, 5],
      ['Cronulla Beach', 36.32662, 59.54048, 3],
      ['Manly Beach', 36.32703, 59.53971, 2],
      ['Maroubra Beach', 36.32677, 59.53979, 1]
    ];
    
  var map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: -34.397, lng: 150.644},
    zoom: 18
  });
  var infoWindow = new google.maps.InfoWindow({map: map});

var marker, i;

    for (i = 0; i < locations.length; i++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }
    
  // Try HTML5 geolocation.
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var pos = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };

      infoWindow.setPosition(pos);
      infoWindow.setContent('موقعیت شما');
      map.setCenter(pos);
    }, 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...