Home  >  Article  >  Web Front-end  >  Use h5 to obtain user geolocation

Use h5 to obtain user geolocation

不言
不言Original
2018-06-12 17:11:242459browse

This article mainly introduces the example code of h5 to obtain geographical positioning. The content is quite good. Now I will share it with you and give it as a reference.

In a recent project, there is a function to obtain surrounding merchants, which requires the use of a geolocation system.

So I thought of using h5 geolocation. After checking the information, I simply The code is encapsulated.

const getPosition = (
  timeout = 10000,
  maximumAge = 60000, 
  enableHighAcuracy = false) => new Promise((resolve, reject) => {
  if (!navigator && !navigator.geolocation)  {
    return reject(new Error('geolocation api not supported'))
  } 

  const success = (loc) => {
      const location = {
        latitude: loc.coords.latitude,  // 纬度
        longitude: loc.coords.longitude,  // 经度
        accuracy: loc.coords.accuracy // 精确度
      }
      resolve(location)
  }

  const error = () => reject('出错了')

  navigator.geolocation.getCurrentPosition(success, error, {
    enableHighAcuracy,  // 指示浏览器获取高精度的位置,默认为false
    timeout,  // 指定获取地理位置的超时时间,默认不限时,单位为毫秒
    maximumAge // 最长有效期,在重复获取地理位置时,此参数指定多久再次获取位置。
  })
})

// 使用示例
getPosition()
.then(pos => pos)
.catch(err => console.log(err))

h5's API for obtaining the geographical location is indeed very useful, but since obtaining the user's geographical location belongs to the user's privacy, it requires the user's authorization.

Whether the user refuses or allows authorization, the site will be cached by the browser, and the user will not be asked again the next time he visits, unless the user manually removes the provision. The address to remove the rule in Chrome is in the settings, as shown below:

#In addition, if the user refuses, you can obtain the latitude and longitude by selecting the IP. Generally, the error will be relatively large.

ipip.net is a website that can obtain user geographical location information through IP.

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Use H5 to imitate WeChat interface

Use html5 canvas encapsulates a pie chart that echarts cannot implement

The above is the detailed content of Use h5 to obtain user geolocation. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn