2014-11-05 2 views
0

Привет всем Мне нужно показать карту google на моем сайте с моим домашним маркером (я использую позицию магазина для него) и центрироваться в позиции пользователя. Стараюсь с:google getLocation не работает в моем скрипте

<script> 
     var myCenter = new google.maps.LatLng('xxx'); 
     var userCenter; 

      function getLocation() { 
       if (navigator.geolocation) { 
        navigator.geolocation.getCurrentPosition(showPosition); 
       } 
      } 

      function showPosition(position) { 
       var latlon = position.coords.latitude + "," + position.coords.longitude; 
       userCenter=new google.maps.LatLng(latlon); 
      } 

     var marker; 

     function initialize() 
     { 
      var mapProp = { 
       center: userCenter, 
       zoom:15, 
       mapTypeId:google.maps.MapTypeId.ROADMAP 
       }; 

      var map=new google.maps.Map(document.getElementById("googleMap"),mapProp); 

      marker=new google.maps.Marker({ 
       position:myCenter, 
       }); 

      marker.setMap(map); 

      var infowindow = new google.maps.InfoWindow({ 
       content:"Casa" 
      }); 

      google.maps.event.addListener(marker, 'click', function() { 
       infowindow.open(map,marker); 
      }); 
     }      

     google.maps.event.addDomListener(window, 'load', initialize); 

    </script> 

, если я не использую userCenter и использовать MyCenter карты работы и показать его в центре MyCenter.

ответ

2

Проблема заключается в порядке выполнения функций. Вы хотите использовать userCenter до того, как пользовательский центр доступен. Это приводит к ошибке (на var mapProp = {center: userCenter, ...}), и поэтому инициализация перестает работать.

Кстати, вы никогда не называете getLocation(). Функция, которая определена только, ничего не делает. Функция только что-то делает, если вы ее называете где-то.

(Кстати 2: navigator.geolocation не является службой Google Это сервис, веб-браузер обеспечивает.)

Я поставил дополнительный комментарий в коде

<script src="http://maps.googleapis.com/maps/api/js?sensor=true"></script> 
<script> 
    var myCenter = new google.maps.LatLng(50.845463, 4.357112); 
    var userCenter; 
    var marker; 
    var map; 

    // sends a request to get the location of the user. 
    // Notice: you will have to wait for the callback (= showPosition) before you have the result of this request. 
    // So you cannot rely only on userCenter. You must use myCenter, until you are sure that showPosition receives the response 
    function getUserLocation() { 
     if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(showPosition); 
     } 
    } 

    // Response of getUserLocation(). The location of the client is known. 
    // Notice: by this time initialize() has been called. initialize() doesn't know anything about userCenter. 
    // userCenter will only get a value when this function is called. 
    function showPosition(position) { 
     userCenter = new google.maps.LatLng(
     position.coords.latitude, 
     position.coords.longitude 
    ); 
     // Now we know the position of the client. We can set the center of the map to this location 
     map.setCenter(userCenter); 
    } 

    // this function initializes Google maps. It is triggered the moment the DOM of the web page is loaded. 
    function initialize() { 
     // let's start the request to get the position of the user 
     getUserLocation(); 

     var mapProp = { 
     center: myCenter, // notice: userCenter is still undefined, you cannot use it yet. 
     zoom:15, 
     mapTypeId:google.maps.MapTypeId.ROADMAP 
     }; 
     map = new google.maps.Map(document.getElementById("googleMap"), mapProp); 
     marker = new google.maps.Marker({ 
     position: myCenter, 
     map: map // this replaces marker.setMap(map); 
     }); 

     var infowindow = new google.maps.InfoWindow({ 
     content: "Casa" 
     }); 
     // a click on the marker opens the infoWindow 
     google.maps.event.addListener(marker, 'click', function() { 
     infowindow.open(map, marker); 
     }); 
    } 
    google.maps.event.addDomListener(window, 'load', initialize); 
</script> 
Смежные вопросы