2015-01-22 4 views
-1

Я использую плагин jquery google maps. Это мой кодjquery google maps не удалось установить местоположение

$(document).ready(function() { 


    var locations = []; 
    locations.push([{ 
     'position': '57.7973333,12.0502107', 
     'bounds': true 
    }, 'Hello World!']); 


    $('#map_canvas').gmap().bind('init', function(ev, map) { 
     for (var i=0; i<locations.length; i+=1) { 

      var loc = locations[i]; 

      /* 
      $('#map_canvas').gmap('addMarker', loc[0]).click(function() { 
       $('#map_canvas').gmap('openInfoWindow', {'content': loc[1]}, this); 
      }); 
      */ 
     } 


     $('#map_canvas').gmap('option', 'zoom', 10); 


     if (navigator.geolocation) { 
      function success(pos) { 
       // Location found, show map with these coordinates 
       //drawMap(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude)); 


       $('#map_canvas').gmap({ 
        'center': new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude) 
       }); 


       //alert(pos.coords.latitude); 
       //alert(pos.coords.longitude); 

       //$('#map_canvas').gmap({ 'center': '42.345573,-71.098326' }); 
      } 
      function fail(error) { 
       $('#map_canvas').gmap({ 'center': '42.345573,-71.098326' }); 
      } 

      // Find the users current position. Cache the location for 5 minutes, timeout after 6 seconds 
      navigator.geolocation.getCurrentPosition(success, fail, {maximumAge: 500000, enableHighAccuracy:true, timeout: 6000}); 
     } else { 
      $('#map_canvas').gmap({ 'center': '42.345573,-71.098326' }); 
     } 
    }); 
}); 

Проблема заключается в том, что я хочу, чтобы установить место (не маркер), где пользователь, но проблема заключается в том, что код не переместит расположение. Он поддерживает его по умолчанию lat/long 0,0. Я не знаю, что не так. Я поставил предупреждение в функцию успеха, и он делает предупреждение.

Кто-нибудь знает, что происходит?

Thanks

ответ

1

Javascript очень часто использует асинхронные процессы. Это означает, что вы (скриптер) отправляете запрос, сопровождаемый обратным вызовом. Javascript берет то, что когда-либо понадобилось, когда он будет готов, он вызовет этот обратный вызов.

В то же время, он продолжается с остальной частью сценария; он не ждет.

Геолокация является одной из тех асинхронных служб. Вы отправляете запрос, остальная часть скрипта продолжается; если и когда геолокация находит местоположение, только тогда вы используете эту функциональность.

Это означает, что вам всегда нужен дефолт; вам всегда нужно писать код по умолчанию, когда сбой геолокации.

Вот пример:

<!DOCTYPE html> 
<html> 
    <head> 
    <meta charset="utf-8"> 
    <title>jquery google maps not able to set location</title> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true"></script> 
    <script src="http://jquery-ui-map.googlecode.com/svn/trunk/ui/jquery.ui.map.js"></script> 
    <script> 
    function initialize() { 
     // we send a request to get the position of the client. 
     // This can take some time, so we don't wait. 
     // We create the map and set a default location. 
     // If and when geolocation found the client's location, we change the center of the map 
     // else, we don't 

     // new map, with default location 
     $('#map_canvas').gmap({ 
     center: '42.345573,-71.098326', 
     zoom: 10 
     }); 
     if (navigator.geolocation) { 
     function success(pos) { 
      // set the center 
      $('#map_canvas').gmap('option', 'center', new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude)); 
     } 
     function fail(error) { 
      // maybe you want to do something here 
     } 
     // start of the request to get the client's position 
     navigator.geolocation.getCurrentPosition(success, fail, {maximumAge: 500000, enableHighAccuracy:true, timeout: 6000}); 
     } 
    } 
    google.maps.event.addDomListener(window, 'load', initialize); 
    </script> 
    <style> 
     #map_canvas { 
     height: 500px; 
     } 
    </style> 
    </head> 
    <body> 
    <div id="map_canvas"></div> 
    </body> 
</html> 
Смежные вопросы