Skip to content Skip to sidebar Skip to footer

Geolocation Map By Default

I have a page show customer location on map and he can drage the marker to be more accurate and the GPS coordinates displayed at the top of page as well. the question is , in somet

Solution 1:

Simplest thing to do: initialize the map to the default location, then let the geolocation reset the position if it is enabled.

code snippet:

var marker;
var map;
var image = "http://maps.google.com/mapfiles/ms/micons/blue.png";

function initialize() {
  var defaultLocation = new google.maps.LatLng(25.074217, 55.510044);
  var lat;

  var mapOptions = {
    zoom: 15,
    center: defaultLocation,
    mapTypeId: google.maps.MapTypeId.HYBRID
  };
  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
  marker = new google.maps.Marker({
    position: defaultLocation,
    map: map,
    draggable: true,
    icon: image
  });
  google.maps.event.addListener(marker, 'position_changed',

    function(event) {
      update();
    });
  navigator.geolocation.getCurrentPosition(function(location) {
    lat = location.coords.latitude;
    lon = location.coords.longitude;

    var city = new google.maps.LatLng(lat, lon);
    var mapOptions = {
      zoom: 15,
      center: city,
      mapTypeId: google.maps.MapTypeId.HYBRID
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);


    marker = new google.maps.Marker({
      position: city,
      map: map,
      draggable: true,
      icon: image
    });

    google.maps.event.addListener(marker, 'position_changed',

      function(event) {
        update();
      });

    update();
  }, function(positionError) {
    alert("getCurrentPosition failed: " + positionError.message);
  }, {
    enableHighAccuracy: true
  });
}

google.maps.event.addDomListener(window, "load", initialize);

function update() {
  var lonlan = marker.getPosition();
  var divLat = document.getElementById("divLat");
  divLat.value = lonlan.lat() + "," + lonlan.lng();
}
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<br />Copy this number and past it in GPS field
<br />
<br />
<input id="divLat" type="text" />
<br />
<br />
<div id="map_canvas"></div>

Post a Comment for "Geolocation Map By Default"