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

通过html5和javascript获取用户地理位置,javascript,html,google-maps,geolocation,ip-geolocation,Javascript,Html,Google Maps,Geolocation,Ip Geolocation,我试图通过html5 geolocation api获取用户的地理位置,并使用以下代码片段: if (navigator.geolocation) { var timeoutVal = 10 * 1000 * 1000; navigator.geolocation.getCurrentPosition( displayPosition, displayError, { enableHighAccuracy: true, timeout: ti

我试图通过html5 geolocation 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]);
  }
});
上述方法的问题在于,很少有用户发现它难以使用。很少有时候,他们会点击拒绝而不是允许,并一直盯着屏幕。因此,从可用性的角度来看,我认为一个好的方法是:

  • 请他们允许

  • 等待3秒钟,如果他们单击拒绝或不响应,请使用IP在地图上显示地理位置

  • 如何完成上述代码片段中的第二步。 请让我知道,谢谢!
    但是,处理

    的更好方法是什么呢?然后,您可以使用这样的geo ip api:


    看看这个tutsplus示例

    好吧,这不是代码答案,更多的是用户体验答案

    从用户体验的角度来看,第一件突出的事情是,在触发浏览器请求许可之前,您缺少提供的信息

    我建议您使用某种叠加框,显示屏幕截图(上面有一个大箭头),在屏幕上显示他们将被请求许可的“位置”。你也可以借此机会告诉他们,如果他们拒绝许可或在10秒钟内不接受许可,将会发生什么情况(例如,他们忽略提示栏)

    我建议您不要默认显示IP位置,因为他们基本上“可能会说”我不同意让您知道我在哪里。然后你展示一张他们所在的大地图,这可能会吓坏一些人!此外,它可能非常不准确

    “不要请求许可,请求原谅”的想法可能在商务开发中起作用,但在UI中不起作用,因为它们不会回来

    我会问你自己,你是否真的也需要高精度,因为它会耗尽用户电池,花费更长的时间,并且可能不会给你带来更多的好处,特别是如果你只需要它粗略地找出它们在哪里的话。如果需要的话,你随时可以稍后再调用它以获得更准确的读数

    如果用户没有单击“拒绝”或“允许”,则可以通过设置超时来实现超时的概念。因此,一旦他们在覆盖框上单击“Ok I'm ready to click allow”(确定我准备好单击允许),启动一个超时,如果它最终超时,那么按照您在上述步骤中告诉他们的操作

    通过使用此方法,您可以强制用户允许或拒绝(忽略),无论哪种方式,它都会将控制权放回您的法庭,并让用户完全了解情况

    虽然这不是一个特定于代码的答案,但从您的JS中可以清楚地看到,“代码实现帮助”并不是这里真正的问题。我希望,如果没有其他事情,这会让您更多地思考您的用户体验。

    这可能会有所帮助: 我用这个做我的东西,效果很好

    例:

    
    函数getLocation(){
    navigator.geolocation.getCurrentPosition(handleSuccess,handleError);
    }
    函数initiate_watchlocation(){
    if(watchProcess==null){
    watchProcess=navigator.geolocation.watchPosition(handleSuccess,handleError);
    }
    } 
    函数stop_watchlocation(){
    if(watchProcess!=null){
    navigator.geolocation.clearWatch(watchProcess);
    }
    } 
    功能手柄成功(位置){
    绘图(位置);
    }
    函数句柄错误(错误){
    开关(错误代码)
    {
    案例错误。权限被拒绝:警报(“用户未共享地理位置数据”);中断;
    案例错误。位置不可用:警报(“无法检测当前位置”);中断;
    案例错误。超时:警报(“检索位置超时”);中断;
    默认值:警报(“未知错误”);中断;
    }
    }
    功能图(位置){
    var container=$('map#u canvas');
    var myLatLong=new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
    变量映射选项={
    中心:迈拉特隆,
    缩放:12,
    mapTypeId:google.maps.mapTypeId.ROADMAP
    };
    var map=new google.maps.map(容器[0],mapOptions);
    css('display','block');
    var marker=new google.maps.marker({
    职位:迈拉特隆,
    地图:地图,
    标题:“我的位置(位置精度:“+Position.coords.accurity+”米),高度:
    +position.coords.altitude+“高度精度:”+position.coords.altitudeAccuracy
    });
    }
    功能图(位置){
    var container=$('map#u canvas');
    var imageUrl=”http://maps.google.com/maps/api/staticmap?sensor=false¢er=“+position.coords.latitude+”,“+
    position.coords.longitude+“&zoom=18&size=640x500&markers=color:blue | label:S |”+
    position.coords.latitude+','+position.coords.longitude;
    container.css({
    “显示”:“块”,
    “宽度”:640
    });
    $('
    找到我的位置
    把手表放在你的位置上
    停车位监视
    Lorem ipsum Door sit amet,为精英们献身,为埃乌斯莫德服务
    暂时性的劳动和财产损失,
    他在乌拉姆科实验室实习,并在普通实验室实习
    在沃鲁帕特·维利特·埃塞的《reprehenderit》一书中,两人或两人之间的冲突
    不适用于任何一方,但不适用于任何一方
    傲慢的人,必须为自己的行为负责


    您可以使用此在线服务轻松获取lat lng:

    关于超时,我认为没有办法干扰浏览器的权限机制(比如,在一定时间后关闭权限弹出窗口)
        <!DOCTYPE html>
    <html>
      <head>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />    
        <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true"></script>    
    
        <script type="text/javascript">
          function getLocation(){
            navigator.geolocation.getCurrentPosition(handleSuccess,handleError);
          }
    
          function initiate_watchlocation() {  
            if(watchProcess == null){
              watchProcess = navigator.geolocation.watchPosition(handleSuccess,handleError);
            }
          } 
    
          function stop_watchlocation() {  
            if(watchProcess != null){
              navigator.geolocation.clearWatch(watchProcess);
            }
          } 
    
          function handleSuccess(position){
            drawMap(position);
          }
    
          function handleError(error){
            switch(error.code)
            {
              case error.PERMISSION_DENIED: alert("User did not share geolocation data");break;  
              case error.POSITION_UNAVAILABLE: alert("Could not detect current position");break;  
              case error.TIMEOUT: alert("Retrieving position timed out");break;  
              default: alert("Unknown Error");break;  
            }
          }
    
    
          function drawMap(position) {
            var container = $('#map_canvas');
            var myLatLong = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
            var mapOptions = {
              center: myLatLong,
              zoom: 12,
              mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            var map = new google.maps.Map(container[0],mapOptions);
            container.css('display','block');
            var marker = new google.maps.Marker({ 
              position: myLatLong,
              map:map,
              title:"My Position (Accuracy of Position: " + position.coords.accuracy + " Meters), Altitude: " 
                + position.coords.altitude + ' Altitude Accuracy: ' + position.coords.altitudeAccuracy
            });
          }
    
          function drawStaticMap(position){
            var container = $('#map_canvas');
            var imageUrl = "http://maps.google.com/maps/api/staticmap?sensor=false&center=" + position.coords.latitude + "," +  
                        position.coords.longitude + "&zoom=18&size=640x500&markers=color:blue|label:S|" +  
                        position.coords.latitude + ',' + position.coords.longitude;  
    
            container.css({
              'display':'block',
              'width' : 640
            });
            $('<img/>',{
              src : imageUrl
            }).appendTo(container);
          } 
        </script>
      </head>
      <body >
        <button id="getLocation">Find My Location</button>
        <div style="text-align:center">
          <button id="initWatch">Put Watch on Your Position</button>
          <button id="stopWatch">Stop Position Watching</button>
        </div>
        <div id="map_canvas" ></div>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
        tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
        cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
        proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    
    
    
      </body>
    </html>
    
    <script src="http://j.maxmind.com/app/geoip.js" charset="ISO-8859-1" type="text/javascript"></script>
    ...
    var time_perm = window.setTimeout(get_by_ip, 3000);
    ...
    function get_by_ip() {
        var lat = geoip_latitude();
        var lng = geoip_longitude();
        map_it(lat, lng);
    }
    ...
    function map_it(lat,lng) {
        // build your map here
    }
    
    if (navigator.geolocation) {
        var timeoutVal = 10 * 1000 * 1000;
        navigator.geolocation.getCurrentPosition(
            displayPosition, 
            displayError,
            { enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
        );
    }
    else {
        displayPosition({coords: {latitude: 40.7142, longitude: -74.0064}})
    }
    ....
    function handleError(error){
        switch(error.code)
        {
            case error.PERMISSION_DENIED: alert("User did not share geolocation data");break;  
            case error.POSITION_UNAVAILABLE: alert("Could not detect current position");break;  
            case error.TIMEOUT: alert("Retrieving position timed out");break;  
            default: alert("Unknown Error");break;  
        }
        displayPosition({coords: {latitude: 40.7142, longitude: -74.0064}});
    }
    
    var position_finders = [                                                                                                                                                                                                              
        function () {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(check_position, check_position);
                return;
            }   
            check_position();
        },  
        function () {
            check_position(JSON.parse(localStorage.getItem('last_location')));
        },  
        function () {
            $.ajax({
                url: 'http://www.google.com/jsapi?key=' + google_api_key,
                dataType: 'script',
                success: check_position
            }); 
        },  
        function () {
            check_position({latitude: 40.7142, longitude: -74.0064}, true);
        }   
    ],
    
    check_position = function (pos, failed) {
        pos = pos || {}; 
        pos = pos.coords ? 
            pos.coords :
            pos.loader ?
            pos.loader.clientLocation :
            pos;
    
        if (typeof pos.latitude === 'undefined' || typeof pos.longitude === 'undefined') {
            position_finders.shift()();
            return;
        }   
    
        localStorage.setItem('last_location', JSON.stringify(pos));
    
        // using your code, I would call this:
        displayPosition(pos);
    };
    
    check_position();