【问题标题】:Can't center google map with ionic framework and ngMap无法使用离子框架和 ngMap 将谷歌地图居中
【发布时间】:2026-02-05 23:55:01
【问题描述】:

我正在使用 Ionic Framework b14 和最新的 ngmap,

我有一个显示地图的视图,但是当我想设置中心时,它不显示我从服务中获取的坐标。

(function() {

  var injectParams = ['$scope', '$stateParams', 'storeFactory'];
  var StoreController = function($scope, $stateParams, storeFactory) {
    var id = $stateParams.storeId;
    $scope.store;


    storeFactory.getStore(id)
      .success(function(store) {
        $scope.store = store;
      }).error(function(error) {
        $scope.status = ' ' + error.message;
      });


    $scope.$on('mapInitialized', function(event, map) {
      var myLatLng = new google.maps.LatLng(store.Latitude, store.Longitud);
      map.setCenter(myLatLng);

    });

  };

  StoreController.$inject = injectParams;

  angular.module('elizondo').controller('StoreController', StoreController);

}());

我想这与服务器响应所需的时间有关,但我不知道如何解决它,您可以给我任何帮助。

谢谢。

【问题讨论】:

    标签: angularjs ionic-framework ionic ng-map


    【解决方案1】:

    你是对的,mapInitialized 监听函数将在来自getStore 的成功回调之前执行。

    您可以将侦听器函数中的地图保存在一个变量中,并在您的回调中使用它:

    var map;
    
    $scope.$on('mapInitialized', function(event, m) {
      map = m;
    });
    
    storeFactory.getStore(id).success(function(store) {
    
      $scope.store = store;
    
      var myLatLng = new google.maps.LatLng(store.Latitude, store.Longitud);
      map.setCenter(myLatLng);
    });
    

    如果您的map 指令范围与StoreController 范围相同,例如:

    <div ng-controller="StoreController">
      <map zoom="8"></map>
    </div>
    

    然后map 对象将在控制器内的$scope 上可用,因此您可以跳过mapInitialized 侦听器函数(除非您也将它用于其他用途),然后执行以下操作:

    storeFactory.getStore(id).success(function(store) {
    
      $scope.store = store;
    
      var myLatLng = new google.maps.LatLng(store.Latitude, store.Longitud);
      $scope.map.setCenter(myLatLng);
    });
    

    【讨论】: