我搜索了几乎所有有关使用 AngularJS 的 Google Maps API 的博客和教程,但找不到解决方案。
基本上,我正在尝试创建一个 map ,其中,
- 标记将通过 GPS 设置。
- 当用户移动标记时,HTML 中的标记坐标值将会改变。
这是 HTML 片段
<div class="row">
<div id="map" style="height: 400px; width: 400px">
</div>
</div>
<div class="row" ng-show="showResult()">
<span ng-bind="latlng.lat"></span><br /> <!--Here I want to see the change -->
<span ng-bind="latlng.lng"></span><br /> <!--Here I want to see the change -->
<span id="current"></span> <!-- Just for testing purpose-->
</div>
这是 AngularJS 片段
$scope.latlng = {lat: -1 ,lng: -1};
google.maps.event.addListener($scope.marker, 'dragend', function (evt) {
document.getElementById('current').innerHTML = '<p>Lat: ' + evt.latLng.lat().toFixed(3) + 'Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
$scope.latlng.lat = evt.latLng.lat();
$scope.latlng.lng = evt.latLng.lng();
console.log($scope.latlng.lat+"\n"+$scope.latlng.lng);
//console.log is just to check if my variables are getting changed or not
$scope.map.setCenter($scope.marker.position);
$scope.marker.setMap($scope.map);
});
我希望我已经表达清楚了。
现在,我的问题是:
当我移动标记时,我可以轻松地在我的当前id中看到更改后的值,但在ng-bind部分中看不到更改后的值。
欢迎任何形式的帮助。
编辑-我也尝试过 ng-model。
最佳答案
这是因为 dragend
事件是在 Angular 事件循环之外触发的,您需要用 $apply
包装更改。功能:
$scope.$apply(function() {
$scope.latlng.lat = evt.latLng.lat();
$scope.latlng.lng = evt.latLng.lng();
});
工作示例
angular.module('mapApp', [])
.controller('mapController', function ($scope) {
$scope.latlng = {lat: -1 ,lng: -1};
$scope.map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: new google.maps.LatLng(59.339025, 18.065818)
});
$scope.marker = new google.maps.Marker({
position: new google.maps.LatLng(59.339025, 18.065818),
map: $scope.map,
draggable:true
});
$scope.showResult = function(){
return true;
}
google.maps.event.addListener($scope.marker, 'dragend', function (evt) {
document.getElementById('current').innerHTML = '<p>Lat: ' + evt.latLng.lat().toFixed(3) + 'Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
$scope.$apply(function() {
$scope.latlng.lat = evt.latLng.lat();
$scope.latlng.lng = evt.latLng.lng();
});
//console.log($scope.latlng.lat+"\n"+$scope.latlng.lng);
$scope.map.setCenter($scope.marker.position);
$scope.marker.setMap($scope.map);
});
});
<script src="https://maps.google.com/maps/api/js"></script>
<script src="https://code.angularjs.org/1.3.15/angular.js"></script>
<div ng-app="mapApp" ng-controller="mapController">
<div class="row">
<div id="map" style="height: 400px; width: 400px"></div>
</div>
<div class="row" ng-show="showResult()">
<span ng-bind="latlng.lat"></span><br /> <!--Here I want to see the change -->
<span ng-bind="latlng.lng"></span><br /> <!--Here I want to see the change -->
<span id="current"></span> <!-- Just for testing purpose-->
</div>
</div>
关于javascript - 谷歌地图的 ng-bind 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35719386/