Support

Account

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

Helping

Geolocation, get the users current location?

  • Hi there, I wanted to work around the geolocation coordinates fields here. I have a situation where I need to populate the initial values of the fields with the users current coordinates taken from the browsers navigator object. I’m not really sure how to get around this – is there something that I need to know before hand?

  • 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);
      }
    }
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Geolocation, get the users current location?’ is closed to new replies.