如何在我的指令中初始化谷歌地图

时间:2015-08-01 07:39:00

标签: angularjs google-maps

在关注google map和angularjs指令的教程演示之后,我得到了示例代码:

HTML

<map-geo-location height="400" width="600"></map-geo-location>

指令JS:

function link(scope, elem, attrs) {
           status = angular.element(document.getElementById('status'));
           mapContainer = angular.element(document.getElementById('map'));

           mapContainer.attr('style', 'height:' + scope.height +
                             'px;width:' + scope.width + 'px');
           $window.navigator.geolocation.getCurrentPosition(mapLocation, geoError);
        }

          function mapLocation(pos) {
              status.html('Found your location! Longitude: ' + pos.coords.longitude +
                          ' Latitude: ' + pos.coords.latitude);

              var latlng = new google.maps.LatLng(pos.coords.latitude,
                                                  pos.coords.longitude);
              var options = {
                zoom: 15,
                center: latlng,
                mapTypeControl: true,
                mapTypeId: google.maps.MapTypeId.ROADMAP
              };

              var map = new google.maps.Map(mapContainer[0], options);

              var marker = new google.maps.Marker({
                position: latlng,
                map: map,
                title:"Your location"
              });
        }

return {
           scope: {
               height: '@',
               width: '@'
           },
           link: link,
           template: template
        };

但是,我注意到,如果我不想加载当前的geoLocation并且只想加载某些给定坐标的地图,则不会加载地图。

为什么?它是由任何异步调用引起的吗?如果是这样,可以解决它吗?

非常感谢!

1 个答案:

答案 0 :(得分:0)

我想通了,只需删除geo get location语句,并确保在link()函数中直接调用以下内容。