Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting users geolocation via html5 and javascript

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

like image 767
whatf Avatar asked Feb 01 '13 09:02

whatf


People also ask

How can we get the geographical position of a user in HTML5?

Approach: To get the geographic position of a user in HTML5, we use geolocation API. Geo-location in HTML5 is used to share the location of the user with some website if the user allows. It uses JavaScript to get the latitude and longitude. Most of the browsers support Geolocation API.

How does the HTML5 Geolocation API locate the client's browser?

How does the HTML5 geolocation API work? HTML5 geolocation detects latitude and longitude coordinates by using the device's GPS (if available on the device) or the device's mobile/WIFI signal (if GPS is not available. The mobile/WIFI signals are triangulated to work out the latitude and longitude.

Does HTML5 have geolocation?

The HTML5 geolocation feature lets you find out the geographic coordinates (latitude and longitude numbers) of the current location of your website's visitor.

How do you fetch geolocation?

The Geolocation API is accessed via a call to navigator. geolocation ; this will cause the user's browser to ask them for permission to access their location data. If they accept, then the browser will use the best available functionality on the device to access this information (for example, GPS).


1 Answers

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
}
like image 166
13 revs Avatar answered Sep 19 '22 19:09

13 revs