Support

Account

Home Forums General Issues Geolocation, get the users current location? Reply To: Geolocation, get the users current location?

  • Hi @maliakmal

    The Google Map Field relies entirely on the google map API and thus it is recommended to consult the Google team for more APIs and for further tutorials.

    It is however important to note that not all browsers support geolocation, it is a device-specific API; some browser/devices support it, while others do not (or cannot).

    You can use the W3C navigator.geolocation property to get the location using the following code:

    var initialLocation;
    var siberia = new google.maps.LatLng(60, 105);
    var newyork = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
    var browserSupportFlag =  new Boolean();
    
    function initialize() {
      var myOptions = {
        zoom: 6,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
    
      // Try W3C Geolocation (Preferred)
      if(navigator.geolocation) {
        browserSupportFlag = true;
        navigator.geolocation.getCurrentPosition(function(position) {
          initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
          map.setCenter(initialLocation);
        }, function() {
          handleNoGeolocation(browserSupportFlag);
        });
      }
      // Browser doesn't support Geolocation
      else {
        browserSupportFlag = false;
        handleNoGeolocation(browserSupportFlag);
      }
    
      function handleNoGeolocation(errorFlag) {
        if (errorFlag == true) {
          alert("Geolocation service failed.");
          initialLocation = newyork;
        } else {
          alert("Your browser doesn't support geolocation. We've placed you in Siberia.");
          initialLocation = siberia;
        }
        map.setCenter(initialLocation);
      }
    }