HTML5 (V) geolocation


HTML5 Geolocation

Locate the user

The HTML5 geolocation API is used to get the user’s geographic location.

Since this feature may infringe the privacy of users, the location information of users is not available unless they agree.

be careful:Geolocation is more accurate for devices with GPS, such as the iPhone.

geographyGeography; location; geo + location; current;

Getcurrentposition() method – return data

T if successful, the getcurrentposition() method returns the object. The latitude, longitude, and accuracy properties are always returned. If available, the other properties below are returned.

attribute describe
coords.latitude Latitude of decimal numbers
coords.longitude Longitude of decimal number
coords.accuracy Position accuracy
coords.altitude Altitude, m above sea level
coords.altitudeAccuracy Altitude accuracy of location
coords.heading Direction, in degrees from due north
coords.speed Speed in meters per second
timestamp Date / time of response

HTML5 – using geolocation

Use the getcurrentposition() method to get the location of the user.

The following example is a simple geolocation example, which can return the longitude and latitude of the user’s location:


	Click to get location
	Data information:
		var x=document.getElementById("demo");

		function getLocation()
                        //Check if geolocation is supported
			if (navigator.geolocation)
				x. InnerHTML = "the browser does not support getting geographic locations. ";
		//Process data and display
		function updatPos(position){
	            var latitude =  position.coords.latitude ; // decimal units
	            var longitude =  position.coords.longitude ; // decimal units
	            var accuracy =  position.coords.accuracy ; // determine the difference between the latitude and longitude and the actual position in M
	            var timestamp =  position.timestamp ; // timestamp
 		    Var date = new date (timestamp); // time format
	            console.log ('longitude coordinates'+ latitude.toFixed (2) ); // keep two decimal places
	            console.log ('latitude coordinates'+ longitude.toFixed (2));
	            console.log ('accuracy '+ accuracy);
	            console.log ('time to obtain location data' + date);

	            x. InnerHTML = latitude:+ latitude.toFixed (2) + "< br > longitude:+ longitude.toFixed (2);   
		function errorLoca(error){
	    	    var str = "";
	    		case 0:
	    		STR: 'location information acquisition failed, failure reason'+ error.message ;break;
                    Case 1 // error code permission_ DENIED
                    STR ='user refused to share their location information '; break;
                    Case 2 // error code position_ UNAVAILABLE
                    STR = 'attempt to get user location data, but failed'; break;
                    Case 3 // error code timeout
                    STR: 'timeout trying to get user's location data'; break;
                console.warn('ERROR(' + error.code + '): ' + error.message);
                x.innerHTML = str;   

Example analysis:

  • Check if geolocation is supported
  • If supported, run the getcurrentposition() method. If not, a message is displayed to the user.
  • If getcurrentposition() runs successfully, a position parameter is returned to the function specified in the parameter updatpos
  • If getcurrentposition() fails to run, an error parameter is returned to the function specified in the parameter errorloca
  • The updatpos() function gets and displays longitude and latitude
  • The errorloca() function prompts an error message

Geolocation object – other interesting methods

Watchposition () – returns the user’s current position and continues to return the updated location of the user as he moves (like GPS on a car).

Clearwatch() – stops the watchposition() method

The following example shows the watchposition() method. You need an accurate GPS device to test this example (such as the iPhone)


var x=document.getElementById("demo");
function getLocation()
    if (navigator.geolocation)
        x. InnerHTML = "the browser does not support getting geographic locations. ";
function updatPos(position)
    x. InnerHTML = latitude:+ position.coords.latitude  + 
    Longitude:+ position.coords.longitude ; 

Problems encountered and Solutions

When running code locally, it starts by defaultChrome browserEach time you click the get geographic location button, the response is slow and it takes a long time to wait.

The error report is as follows:

Several reasons for the failure were found by consulting the data.

Error prompted by chrome console: network location provider at ‘ ‘ : No response received.

Chrome browser access to location-based services in foreign countries, there are greater restrictions, will also cause location failure, and the failure rate is high.

Replace it with the system’s ownIE browser, perfect operation

Try againFirefox browserOperation and successful positioning

Locate the cause of the failure

1. The first case

Browser does not support native location interface, such as browser of lower version of IE, message field containsBrowser not Support html5 geolocationInformation.

2. The second case

The user has disabled the location permission and needs to enable the location permission. The message field containsGeolocation permission denied

3. The third case

Browsers prohibit location requests from non secure domains, such as chrome and ios10, which need to be upgraded to HTTPS. The message field containsGeolocation permission careful:Chrome won’t ban itlocalhostThe location of domain name under HTTP protocol.

4. The fourth case

Browser location timeout, including native timeout, can be appropriately increased to reduce this phenomenon. An individual browser itself is not friendly to the positioning interface, and it will time out and return failure. The message field containsGeolocation time outInformation.

5. The fifth case

Chrome, Firefox and some shell browsers access location-based services in foreign countries, there are greater restrictions, also will cause location failure, and the failure rate is high.

Recommended Today

The course of using Chinese software of poedit Pro

Poedit pro (formerly known as poedit) is a free (professional version charge), open source and cross platform gettext class (. Po format, gettext is used in the application program for program internationalization) International Translation editor. It is also one of the most widely used software of the same type. At present, it is available in […]