通过html5和javascript获取用户地理位置

wha*_*atf 14 javascript html5 google-maps geolocation ip-geolocation

我试图通过html5 geolcation api获取用户地理位置,我使用以下代码片段:

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]);
  }
});
Run Code Online (Sandbox Code Playgroud)

上述方法的问题在于,很少有用户发现难以使用.几乎没有时间,他们点击了拒绝而不是允许并继续盯着屏幕.所以从可用性的角度来看,我认为一个好的方法是:

  1. 请他们许可.

  2. 等待3秒钟,如果他们点击拒绝或没有响应,请使用IP在地图上显示地理位置.

如何完成上述代码片段中的第二步.请让我知道,谢谢!但是,什么是更好的处理方式

Onu*_*rım 16

这是我前一段时间写过并最近更新的脚本(geolocator.js).

更新:Geolocator v2已发布.

特征:

  • HTML5地理位置(通过用户权限)
  • 按IP位置
  • 地理编码(地址坐标)
  • 反向地理编码(从坐标查找地址)
  • 完整的地址信息(街道,城镇,社区,地区,国家,国家代码,邮政编码等...)
  • 回退机制(从HTML5地理定位到IP地理查找)
  • 观察地理位置
  • 获取距离矩阵和持续时间
  • 计算两个地理点之间的距离
  • 获取时区信息
  • 获取客户端IP
  • 支持Google Loader(动态加载Google地图)
  • 动态创建Google地图(带标记,信息窗口,自动调整缩放)
  • 非阻塞脚本加载(在不中断页面加载的情况下即时加载外部源)

观看现场演示.
请参阅API文档.

Geolocator示例屏幕截图

用法:

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);
});
Run Code Online (Sandbox Code Playgroud)

示例输出:

{
    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
}
Run Code Online (Sandbox Code Playgroud)