通过html5和javascript获取用户地理位置 [英] getting users geolocation via html5 and javascript

查看:94
本文介绍了通过html5和javascript获取用户地理位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  if(navigator.geolocation){
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.getCurrentPosition(
displayPosition,
displayError,
{enableHighAccuracy:true,timeout:timeoutVal,maximumAge:0}
);
}
else {
//在这里做一些东西
}


函数displayPosition(position){

//配置
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.创建地图
2.缩放
3.居中地图
4.设置地图的类型
* /
var map = new google.maps.Map(document.getElementById('canvas'),{
zoom:myZoom,
center:new google.maps.LatLng(defaultLat,defaultLng),
mapTypeId:google.maps.MapTypeId.ROADMAP
});


});
//将地图放置在标记坐标上
map.setCenter(myMarker.position);
//在地图上添加标记
myMarker.setMap(map);


函数displayError(错误){
var errors = {
1:'Permission denied',
2:'Position unavailable',
3:'请求超时'
};
alert(Error:+ errors [error.code]);
}
});

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


  1. 请他们允许。如果他们点击拒绝或不回应,请等待3秒钟,然后使用IP在地图上显示地理定位。


  2. 请让我知道,谢谢!
    然而,什么是更好的处理方式

    解决方案

    这是一个脚本(



    用法:



      var options = {
    enableHighAccuracy:true,
    timeout:6000,
    maximumAge:0,
    desiredAccuracy:30,// meters
    fallbackToIP:true,//如果地理位置失败或被拒绝,则通过IP获取位置
    addressLookup:true,//需要Google API密钥
    timezone:true,//需要Google API密钥
    map:我的地图//创建一个Google地图。需要Google API密钥
    };
    geolocator.locate(options,function(err,location){
    console.log(err || location);
    });

    输出示例

    {
    coords:{
    latitude:37.4224764,
    longitude:-122.0842499,
    accuracy :30,
    海拔:null,
    altitudeAccuracy:null,
    航向:null,
    速度:null
    },
    地址:{
    commonName:,
    street:Amphitheatre Pkwy,
    route:Amphitheatre Pkwy,
    streetNumber:1600,
    neighborhood:,
    镇:b $ b市:山景城b $ b地区:圣克拉拉县
    州加利福尼亚州$ b $州stateCode:CA $
    postalCode:94043,
    国家:美国,
    countryCode:美国
    },
    格式化地址:1600 Amphitheatre Parkway,Mountain View,CA 94043,USA,
    类型:ROOFTOP,
    placeId:ChIJ2eU
    时区:{
    id:America / Los_Angeles,
    名称: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
    }


    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

    解决方案

    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.

    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
    }
    

    这篇关于通过html5和javascript获取用户地理位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆