【发布时间】:2016-08-03 06:08:33
【问题描述】:
我正在使用 Google 地图学习 Angular,但在由 ng-if 指令控制的 div 中渲染地图时遇到了困难。
对于我的应用程序,我希望在接收到来自 $scope.location 函数的坐标后渲染地图。然后我会单击一个按钮并调用 $scope.myRide 以便在地图上放置一个标记。但是,正在发生的事情是在我单击按钮之前地图不会呈现。 $scope.map 中的坐标用作占位符,直到从 $scope.location 接收到实际坐标。 任何帮助将不胜感激:)
angular.module('MapView',[])
.config(function($stateProvider){
$stateProvider
// the state will go on the html that you want route the user.
.state('mapView', {
url: '/mapView',
templateUrl: 'app/mapView/mapView.html',
controller: function($scope){
$scope.map = { center: { latitude: 38, longitude: -122 }, zoom: 15 };
$scope.output = document.getElementById("loc");
$scope.maker = {};
$scope.coords = {};
$scope.mockUsers = [{username: 'young', mess: 'I need a ride at 9am'},{username: 'young', mess: 'I need a ride at 9am'}, {username: 'young', mess: 'I need a ride at 9am'}]
$scope.location = function(){
if (!navigator.geolocation){
output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
return;
}
navigator.geolocation.getCurrentPosition(function(position){
console.log('current position',position.coords)
$scope.map.center.latitude = position.coords.latitude;
$scope.coords.lat = position.coords.latitude; //added this
$scope.map.center.longitude = position.coords.longitude;
$scope.coords.lon = true; // added this
}, function(){
$scope.output.innerHTML = "Unable to retrieve your location";
});
}()
$scope.myRide = function(){
$scope.maker.latitude = $scope.map.center.latitude;
$scope.maker.longitude = $scope.map.center.longitude;
}
},
controllerAs: 'LoginCtrl'
});
})
以下是 HTML:
<div ui-sref='mapView' >
<div ng-show = "coords.lon == true">Hello</div>
<div id="loc"></div>
<div id="mapDiv" ng-if="coords.lon">
<ui-gmap-google-map center='map.center' zoom='map.zoom' maker=>
<ui-gmap-marker coords="maker" icon="icon" idkey="1"></ui-gmap-marker>
</ui-gmap-google-map>
</div>
<div class="btn-Center">
<button class="btn btn-danger" ng-click='myRide()' >Ride</button>
</div>
<div id="mapUsers">
<div class="clear" ng-repeat='user in mockUsers'>
<div class="mapUserImg">
<img class="img-responsive" src="http://falconbus.in/images/site/user_icon.png">
</div>
<h1> {{ user.username }} </h1>
<p> {{ user.mess}} </p>
</div>
</div>
</div>
【问题讨论】:
-
尝试通过 ng-show 更改 ng-if,ng-if 打开一个新范围,因此您可能会丢失您对 ng-show 使用相同范围的绑定。
-
谢谢,但不幸的是,ng-show 让情况变得更糟。地图仍然不会自动渲染 - 点击按钮会打开地图窗口,但它是空白的。
标签: javascript angularjs google-maps google-geolocation angularjs-ng-if