javascript - google getLocation 函数在我的脚本中不起作用

标签 javascript google-maps

大家好,我需要在我的网站上显示一个谷歌地图,其中包含我的家标记(我使用商店位置)并以用户位置为中心。我尝试:

<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,则 map 将正常工作并以 MyCenter 为中心显示。

最佳答案

问题在于函数的执行顺序。您希望在 userCenter 可用之前使用 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>

关于javascript - google getLocation 函数在我的脚本中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26754939/

相关文章:

javascript - ExpressJS Cors 无法在 Angular 上运行

javascript - 从浏览器建立任意 TCP 连接

javascript - 制作一个可以作为函数调用的对象

javascript - 无法在 keydown 上运行 .live...有什么建议吗?

javascript - Angular/ Material 模式对话框不适用于谷歌地图的形状点击

jquery - 谷歌地图 + jQuery : rendering bug

objective-c - MKMapVIew 问题,我的定位点未按正确方向显示(我正在使用 mkmapview 的罗盘模式)

javascript - 为什么在对象的函数属性中声明变量之前可以引用它?

javascript - 如何检查谷歌地图是否已满载?

css - 如何使用 Google map 获得 2 列布局?