1

我是 Javascript 和 Google 地图的新手,我正在尝试使用 Google Developers 网站上提供的信息在我的地图上添加一个标记。尽管地图显示在当前位置上,并且我在 Javascript 控制台上没有收到任何错误,但由于某种原因,标记仍未显示。关于为什么会发生这种情况的任何想法?提前致谢。

这是我的代码:

            function initialize() {
              var myOptions = {
                zoom: 14,
                mapTypeId: google.maps.MapTypeId.ROADMAP
              };

              var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

              // Try W3C Geolocation (Preferred)
              if(navigator.geolocation) {
                browserSupportFlag = true;
                navigator.geolocation.getCurrentPosition(function(position) {
                  initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
                  map.setCenter(initialLocation);
                }, function() {
                  handleNoGeolocation(browserSupportFlag);
                });
              }
              // Browser doesn't support Geolocation
              else {
                browserSupportFlag = false;
                handleNoGeolocation(browserSupportFlag);
              }

              function handleNoGeolocation(errorFlag) {
                if (errorFlag == true) {
                  alert("Geolocation service failed.");
                  initialLocation = newyork;
                } else {
                  alert("Your browser doesn't support geolocation. We've placed you in Siberia.");
                  initialLocation = siberia;
                }
                map.setCenter(initialLocation);
              }

                var marker = new google.maps.Marker({
                    position: initialLocation,
                    title:"You are here!"

                 });
                 // should add the marker to the map
                 marker.setMap(map);

            };
4

1 回答 1

0

地理位置服务是异步的。您需要在其回调函数中使用坐标。很难从您发布的内容中判断地理位置所采用的路径,如果成功,这里的代码将执行此操作。

        if(navigator.geolocation) {
            browserSupportFlag = true;
            navigator.geolocation.getCurrentPosition(function(position) {
              initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
              map.setCenter(initialLocation);
              var marker = new google.maps.Marker({
                position: initialLocation,
                title:"You are here!"

                });
              // should add the marker to the map
              marker.setMap(map);
            }, function() {
              handleNoGeolocation(browserSupportFlag);
            });
于 2012-11-28T19:42:01.860 回答