我有一个谷歌地图指令,显示从一个地方到另一个地方的旅行。
在应用程序运行期间,我要求用户许可并将当前位置添加到范围:
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(function(position) {
$rootScope.myLocation = {}
$rootScope.myLocation.lat = position.coords.latitude;
$rootScope.myLocation.long = position.coords.longitude;
$rootScope.$apply()
});
}
在某些视图中,我根据当前位置生成带有指令的谷歌地图:
<g-map id="transit" origin="{{myLocation.lat}},{{myLocation.long}}" destination="{{location.lat}},{{location.long}}" type='TRANSIT' class="map"></g-map>
问题在于,如果在用户批准位置请求之前生成地图,则谷歌地图会显示错误的响应(因为没有原始位置)。我想要做的是将默认位置作为我的来源,并从浏览器location-api更新回调中的谷歌地图。
有没有像我可以使用的指令方法?这是我的指示:
directive('gMap', function(){
return{
restrict: 'E',
replace: true,
scope: {
origin: '@origin',
destination: '@destination',
},
template: "<div id='map'></div>",
link: function(scope, element, attrs){
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.Map(document.getElementById(attrs.id), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('panel'));
var request = {
origin: attrs.origin,
destination: attrs.destination,
travelMode: google.maps.DirectionsTravelMode[attrs.type]
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}else(
console.log(status)
)
});
}
};
}
答案 0 :(得分:1)
好吧,首先不要使用这样的东西:origin =&#34; {{myLocation.lat}},{{myLocation.long}}&#34;。这很奇怪。这是因为您永远不知道如何以及何时计算和更新您的属性。您可以为此设置不同的值。您还需要正确跟踪这些属性。
更好的方法是在范围属性上使用双向绑定,并将数据作为对象传递到那里:
<g-map id="transit" origin="myLocation" destination="location" type='TRANSIT' class="map"></g-map>
在这种情况下,您将指令声明为
...
scope: {
origin: '=',
destination: '=',
}
...
您可以指定默认位置。 然后,您可以轻松地查看原点并更新结果。
答案 1 :(得分:1)
在调用getCurrentPosition()
...
$rootScope.myLocation = {lat: 47, long: 120};
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(function(position) {
$rootScope.myLocation.lat = position.coords.latitude;
$rootScope.myLocation.long = position.coords.longitude;
$rootScope.$apply()
});
}
指令中的link
内,在origin
和destination
上设置了一个监视...
function updateMap (newValue) {
// move your map update code here and position the map to newValue
}
scope.$watch('origin', updateMap);
scope.$watch('destination', updateMap);