如何在Google地图上移动标记

时间:2016-07-21 13:47:13

标签: google-maps google-maps-markers angular-google-maps

我正在学习Google Maps API,我正试图在地图上移动一个对象。我创建了一个测试页面,在开始时显示标记,但在调用增加经度的函数后,它会从地图中删除标记。控制台中没有错误。有人可以查看我的代码并帮我弄清楚为什么会这样吗? Javascript文件:

var app = angular.module('angularGoogleMapsTestApp', ['uiGmapgoogle-maps']);

var increment = 2.02;
var startingLongitude = -122.44;
var startingLatitude = 37.769;

  app.controller('angularGoogleMapCtrl', function ($scope, $log, $rootScope) {

$scope.map = {center: {latitude: 37.7699298, longitude: -122.4469157}, zoom: 12};
$scope.markers = [];

$scope.removeMarkers = function () {
    $scope.markers = [];
}

function init() {
    $scope.markers.push(
            {
                id: 0,
                latitude: startingLatitude,
                longitude: startingLongitude
            });

    $log.info(JSON.stringify($scope.markers));
}

$scope.moveMarker = function () {
    var old = $scope.markers[0].longitude;
     $scope.markers.splice(0, 1);
    $scope.markers.push(
            {
                id: 0,
                latitude: startingLatitude,
                longitude: (old + increment)
            });
    $log.info(JSON.stringify($scope.markers));
 };

  init();

});

和html:

<!DOCTYPE html>
 <head>
<meta charset="utf-8">
<title>ngMap Tests</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="bower_components/angularjs/angular.js"></script>
<script src="bower_components/lodash/dist/lodash.js"></script>
<script src='bower_components/angular-google-maps/dist/angular-    google-maps.js'></script>
<script src="angularGoogleMapsTestApp.js"></script>
<style>
    .angular-google-map-container { height: 400px; }

</style>
</head>
<body ng-app="angularGoogleMapsTestApp">
<h3>Angular Google Maps Test</h3>

<p>Test showing adding and removing markers on Angular Google Maps
    (from: <a href="http://angular-ui.github.io/angular-google-maps/#!/">
        Angular Google Maps</a>)</p>

<div ng-controller="angularGoogleMapCtrl">
    <input ng-click="moveMarker()" type="button" value="moveMarker">
    <input ng-click="removeMarkers()" type="button" value="Remove markers">

    <div style="height:500px">
        <ui-gmap-google-map center='map.center' zoom='map.zoom'>
            <ui-gmap-markers models="markers" coords="'self'" modelsbyref="false"/>
        </ui-gmap-google-map>
    </div>
    </div>
    </body>
    </html>

1 个答案:

答案 0 :(得分:0)

如果您使用的是Angular Google地图v1.2.0或更高版本,则您的标记对象需要idKeydescribed here in the docs。您可以使用id更改当前的idKey密钥,如下所示:

$scope.markers.push({
    idKey: 0,
    latitude: startingLatitude,
    longitude: startingLongitude
});