getting users geolocation via html5 and javascript
Asked Answered
S

8

13

I am trying to get the users geolocation via the html5 geolcation api, and i use the following snippet for it:

if (navigator.geolocation) {
    var timeoutVal = 10 * 1000 * 1000;
    navigator.geolocation.getCurrentPosition(
      displayPosition, 
      displayError,
      { enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
    );
  }
  else {
     // DO SOME STUFF HERE
  }


  function displayPosition(position) {

    // configuration
    var myZoom = 12;
    var myMarkerIsDraggable = true;
    var myCoordsLenght = 6;
    var defaultLat = position.coords.latitude;
    var defaultLng = position.coords.longitude;
    document.getElementById('latitude').value = defaultLat;
    document.getElementById('longitude').value = defaultLng;
    /*
      1. creates the map
      2. zooms
      3. centers the map
      4. sets the map’s type
    */
    var map = new google.maps.Map(document.getElementById('canvas'), {
      zoom: myZoom,
      center: new google.maps.LatLng(defaultLat, defaultLng),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });


    });
    // centers the map on markers coords
    map.setCenter(myMarker.position);
    // adds the marker on the map
    myMarker.setMap(map);
  }

  function displayError(error) {
    var errors = { 
      1: 'Permission denied',
      2: 'Position unavailable',
      3: 'Request timeout'
    };
    alert("Error: " + errors[error.code]);
  }
});

The trouble with the above approach is that, few of the users have found it difficult to use. Few of the times, they have clicked Deny instead of Allow and keep staring on the screen. So from usability point of view, I think a good approach would be:

  1. Ask them for permission.

  2. Wait for 3 seconds, if they click deny or don't respond, use IP to show the geolcation on the map.

How can I accomplish the second step in my above snippets. Please let me know, thanks! However, what would be a better way to handle

Spaulding answered 1/2, 2013 at 9:5 Comment(1)
Is your error handler (displayError()) not being called when the user clicks Deny or when the request times out? If it is being called (as it should), it's there that you'd want to do your second step (use the user's IP to do geolocation).Jollenta
W
16

Here is a script (geolocator.js) I wrote some time ago and updated recently.

Update: Geolocator v2 is released.

Features:

  • HTML5 geolocation (by user permission)
  • Location by IP
  • Geocoding (coordinates from address)
  • Reverse Geocoding (address lookup from coordinates)
  • Full address information (street, town, neighborhood, region, country, country code, postal code, etc...)
  • Fallback mechanism (from HTML5-geolocation to IP-geo lookup)
  • Watch geographic position
  • Get distance matrix and duration
  • Calculate distance between two geographic points
  • Get timezone information
  • Get client IP
  • Supports Google Loader (loads Google Maps dynamically)
  • Dynamically creates Google Maps (with marker, info window, auto-adjusted zoom)
  • Non-blocking script loading (external sources are loaded on the fly without interrupting page load)

See a live demo.
See API documentation.

Geolocator Example Screenshot

Usage:

var options = {
    enableHighAccuracy: true,
    timeout: 6000,
    maximumAge: 0,
    desiredAccuracy: 30, // meters
    fallbackToIP: true, // get location by IP if geolocation fails or rejected
    addressLookup: true, // requires Google API key
    timezone: true, // requires Google API key
    map: "my-map" // creates a Google map. requires Google API key
};
geolocator.locate(options, function (err, location) {
    console.log(err || location);
});

Example Output:

{
    coords: {
        latitude: 37.4224764,
        longitude: -122.0842499,
        accuracy: 30,
        altitude: null,
        altitudeAccuracy: null,
        heading: null,
        speed: null
    },
    address: {
        commonName: "",
        street: "Amphitheatre Pkwy",
        route: "Amphitheatre Pkwy",
        streetNumber: "1600",
        neighborhood: "",
        town: "",
        city: "Mountain View",
        region: "Santa Clara County",
        state: "California",
        stateCode: "CA",
        postalCode: "94043",
        country: "United States",
        countryCode: "US"
    },
    formattedAddress: "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
    type: "ROOFTOP",
    placeId: "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
    timezone: {
        id: "America/Los_Angeles",
        name: "Pacific Standard Time",
        abbr: "PST",
        dstOffset: 0,
        rawOffset: -28800
    },
    flag: "//cdnjs.cloudflare.com/ajax/libs/flag-icon-css/2.3.1/flags/4x3/us.svg",
    map: {
        element: HTMLElement,
        instance: Object, // google.maps.Map
        marker: Object, // google.maps.Marker
        infoWindow: Object, // google.maps.InfoWindow
        options: Object // map options
    },
    timestamp: 1456795956380
}
Wedekind answered 1/2, 2013 at 9:5 Comment(0)
R
3

You would then use a geo ip api like this one:

http://freegeoip.net/static/index.html

Richburg answered 1/2, 2013 at 14:24 Comment(0)
B
2

Ok so this is not a code answer, more of an User Experience answer.

From a UX standpoint, the first thing that stands out is the lack of information you are offering before you trigger the browser to ask them for permission.

I suggest you have some sort of overlay box showing a screen shot (with a large arrow on it) demonstrating "where" on the screen that they are going to get asked for permission. Also you can take that opportunity to tell them what will happen if they deny permission or fail to accept it within say 10 seconds (ie. where they ignore the prompt bar).

I suggest you don't default to showing the IP location, because they essentially 'could be saying' I don't agree to letting you know where I am. Then you show a big map of where they are, that may freak a few people out that clicked deny! Besides it may be very inaccurate.

The idea of "don't ask for permission ask for forgiveness", may work in Biz dev, but not in UI as they just don't come back.

I would ask yourself if you really need high accuracy too, because it will drain user battery, take longer, and may not give you much more bang for your buck, especially if you only need it to find out loosely where they are. You can always call it again later for a more accurate reading if you need to.

The concept of timing out if they don't click deny or allow could be achieved with a setTimeout. So once they click "Ok I'm ready to click allow" on your overlay box, kick off a timeout and if it does eventually timeout then do what you told them you would do in the above step.

By using this method, you force the user to either allow or deny(ignore), either-way it puts control back in your court, and keep the user totally informed.

Although this is not a code specific answer, it is clear from your JS that "code implementation help" is not really the issue here. I hope if nothing else this gets you thinking a little more about your User Experience.

Blinding answered 4/2, 2013 at 17:37 Comment(2)
Very well put. I want to second the point made about defaulting to show IP Location when they initially Deny showing their location - this would definitely make the user feel "unsafe" visiting your site, because they won't necessarily be aware that your using an IP to Geolocation service once they deny HTML5 geolocation.Snowy
I've actually done an assessment on a few of the free IP to Geolocation services out there and compared their accuracy on a map. You can check it out here if your deciding on a service to use: svignara.github.com/geolocation.html You can check my codebase on github to see how to make the ajax requests to these services.Snowy
I
0

look at this tutsplus example http://mobile.tutsplus.com/tutorials/mobile-web-apps/html5-geolocation/

Ibrahim answered 3/2, 2013 at 11:6 Comment(1)
i want an answer for webapp.Spaulding
D
0

This, might be of help: http://jsfiddle.net/sandesh2302/FghFZ/ I used this for my stuff, it worked fine.

Ex:

    <!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />    
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true"></script>    

    <script type="text/javascript">
      function getLocation(){
        navigator.geolocation.getCurrentPosition(handleSuccess,handleError);
      }

      function initiate_watchlocation() {  
        if(watchProcess == null){
          watchProcess = navigator.geolocation.watchPosition(handleSuccess,handleError);
        }
      } 

      function stop_watchlocation() {  
        if(watchProcess != null){
          navigator.geolocation.clearWatch(watchProcess);
        }
      } 

      function handleSuccess(position){
        drawMap(position);
      }

      function handleError(error){
        switch(error.code)
        {
          case error.PERMISSION_DENIED: alert("User did not share geolocation data");break;  
          case error.POSITION_UNAVAILABLE: alert("Could not detect current position");break;  
          case error.TIMEOUT: alert("Retrieving position timed out");break;  
          default: alert("Unknown Error");break;  
        }
      }


      function drawMap(position) {
        var container = $('#map_canvas');
        var myLatLong = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
        var mapOptions = {
          center: myLatLong,
          zoom: 12,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(container[0],mapOptions);
        container.css('display','block');
        var marker = new google.maps.Marker({ 
          position: myLatLong,
          map:map,
          title:"My Position (Accuracy of Position: " + position.coords.accuracy + " Meters), Altitude: " 
            + position.coords.altitude + ' Altitude Accuracy: ' + position.coords.altitudeAccuracy
        });
      }

      function drawStaticMap(position){
        var container = $('#map_canvas');
        var imageUrl = "http://maps.google.com/maps/api/staticmap?sensor=false&center=" + position.coords.latitude + "," +  
                    position.coords.longitude + "&zoom=18&size=640x500&markers=color:blue|label:S|" +  
                    position.coords.latitude + ',' + position.coords.longitude;  

        container.css({
          'display':'block',
          'width' : 640
        });
        $('<img/>',{
          src : imageUrl
        }).appendTo(container);
      } 
    </script>
  </head>
  <body >
    <button id="getLocation">Find My Location</button>
    <div style="text-align:center">
      <button id="initWatch">Put Watch on Your Position</button>
      <button id="stopWatch">Stop Position Watching</button>
    </div>
    <div id="map_canvas" ></div>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>



  </body>
</html>
Doretheadoretta answered 4/2, 2013 at 17:46 Comment(0)
S
0

You can use this online service to get the lat lng easily:

http://dev.maxmind.com/geoip/javascript

Regarding the timeout, I don't think there's a way to interfere with the browsers permission mechanism (as in, to close that permission popup after a certain amount of seconds) - though I would gladly be proven wrong. What you could do would be to set a timer and after three seconds, get the IP based geolocation and set the map to it (or, refresh the page after 3 seconds, and set a cookie that triggers the IP based geo and not the HTML5 geo, but that's a bit over the top if you ask me).

Then, if they give permission, it would refresh the map with the HTML5 geolocation (which should be much more accurate). You can also encapsulate the IP geo fallback into a function and use it if they don't have HTML5 geolocation or they hit deny.

Here's a fiddle: http://jsfiddle.net/mfNCn/1/

Here's the rough cut from the fiddle:

<script src="http://j.maxmind.com/app/geoip.js" charset="ISO-8859-1" type="text/javascript"></script>
...
var time_perm = window.setTimeout(get_by_ip, 3000);
...
function get_by_ip() {
    var lat = geoip_latitude();
    var lng = geoip_longitude();
    map_it(lat, lng);
}
...
function map_it(lat,lng) {
    // build your map here
}

(I hesitate to put the whole code chunk onto here, as it's rather lengthy, so check the fiddle for the rest and full implementation)

Spithead answered 6/2, 2013 at 21:40 Comment(0)
T
0

If there is a timeout or the user denies the request, I would set a default location like New York, NY (40.7142, -74.0064). If a user denies a request, they have to also expect that you won't know their location so choosing an intelligible default is the next best thing.

Using a default without changing your code much can be accomplished by calling displayPosition({coords: {latitude: 40.7142, longitude: -74.0064}}) in two places:

if (navigator.geolocation) {
    var timeoutVal = 10 * 1000 * 1000;
    navigator.geolocation.getCurrentPosition(
        displayPosition, 
        displayError,
        { enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
    );
}
else {
    displayPosition({coords: {latitude: 40.7142, longitude: -74.0064}})
}
....
function handleError(error){
    switch(error.code)
    {
        case error.PERMISSION_DENIED: alert("User did not share geolocation data");break;  
        case error.POSITION_UNAVAILABLE: alert("Could not detect current position");break;  
        case error.TIMEOUT: alert("Retrieving position timed out");break;  
        default: alert("Unknown Error");break;  
    }
    displayPosition({coords: {latitude: 40.7142, longitude: -74.0064}});
}

On http://nearbytweets.com I use a "queue" of functions for finding a user's location, looping through the queue until one of them finds a valid location. The last function returns New York, NY, which means all other attempts have failed. Here's a sample of the code modified slightly:

var position_finders = [                                                                                                                                                                                                              
    function () {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(check_position, check_position);
            return;
        }   
        check_position();
    },  
    function () {
        check_position(JSON.parse(localStorage.getItem('last_location')));
    },  
    function () {
        $.ajax({
            url: 'http://www.google.com/jsapi?key=' + google_api_key,
            dataType: 'script',
            success: check_position
        }); 
    },  
    function () {
        check_position({latitude: 40.7142, longitude: -74.0064}, true);
    }   
],

check_position = function (pos, failed) {
    pos = pos || {}; 
    pos = pos.coords ? 
        pos.coords :
        pos.loader ?
        pos.loader.clientLocation :
        pos;

    if (typeof pos.latitude === 'undefined' || typeof pos.longitude === 'undefined') {
        position_finders.shift()();
        return;
    }   

    localStorage.setItem('last_location', JSON.stringify(pos));

    // using your code, I would call this:
    displayPosition(pos);
};

check_position();

Here's what each position_finder does:

  1. Tries navigator.geolocation.
  2. Tries pulling their last location from localStorage
  3. Uses Google Loader to find location via I.P.
  4. Uses New York, NY
Treasurer answered 8/2, 2013 at 23:3 Comment(0)
G
-1

From UI point of view, I would follow these steps:

A) show a nice text box explaining what's going to happen next (I.e. 'the browser will ask you to grant a permission', 'click allow', etc) and asking to push a button to proceed B) display the map as you do now

Geldens answered 7/2, 2013 at 7:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.