移动谷歌地图中心javascript api

时间:2012-10-02 22:24:46

标签: javascript maps

在我的项目中,我想将地图的中心移动到新的坐标。这是我对地图的代码

function initialize() {
    var mapOptions = {
      center: new google.maps.LatLng(0, 0),
      zoom: 4,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
        mapOptions);
  }
  function moveToLocation(lat, lng){
     var center = new google.maps.LatLng(lat, lng);
     var map = document.getElementById("map_canvas");
     map.panTo(center);

  }

moveToLocation函数会被调用,但地图不会重新居中。知道我错过了什么吗?

2 个答案:

答案 0 :(得分:67)

您的问题是在moveToLocation中,您使用document.getElementById尝试获取Map对象,但这只会获得HTMLDivElement,而不是google.maps.Map {1}}你期待的元素。因此,您的变量map没有panTo函数,这就是它无效的原因。你需要的是将map变量放在某个地方,它应该按计划运行。您可以像这样使用全局变量:

var map;      // global variable

function initialize() {
    var mapOptions = {
        center: new google.maps.LatLng(0, 0),
        zoom: 4,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    // assigning to global variable:
    map = new google.maps.Map(document.getElementById("map_canvas"),
        mapOptions);
}

function moveToLocation(lat, lng){
    var center = new google.maps.LatLng(lat, lng);
    // using global variable:
    map.panTo(center);
}

请在此处查看jsFiddle:http://jsfiddle.net/fqt7L/1/

答案 1 :(得分:1)

动态显示Google Maps API,获取数据库中的数据以显示地点,lat,long以及使用AngularJS在中心显示地图标记。由Sureshchan完成......

Screenshot of Google Maps

$(function() {
    $http.get('school/transport/scroute/viewRoute?scRouteId=' + scRouteId).success(function(data) {
        console.log(data);

        for (var i = 0; i < data.viewRoute.length; i++) {
            $scope.view = [];
            $scope.view.push(data.viewRoute[i].stoppingName, data.viewRoute[i].latitude, data.viewRoute[i].longitude);
            $scope.locData.push($scope.view);
        }            

        var locations = $scope.locData;
        var map = new google.maps.Map(document.getElementById('map'), {                    
            mapTypeId : google.maps.MapTypeId.ROADMAP
        });
        var infowindow = new google.maps.InfoWindow();
        var bounds = new google.maps.LatLngBounds();
        var marker, j;

        for (j = 0; j < locations.length; j++) {
            marker = new google.maps.Marker({
                position : new google.maps.LatLng(locations[j][1], locations[j][2]),
                map : map
            });

            google.maps.event.addListener(marker, 'click', (function(marker, j) {
                bounds.extend(marker.position);
                return function() {
                    infowindow.setContent(locations[j][0]); 
                    infowindow.open(map, marker);
                    map.setZoom(map.getZoom() + 1);
                    map.setCenter(marker.getPosition());
                }
            })(marker, j));
        };
        map.fitBounds(bounds);
    });
});