【问题标题】:Passing variables from Controller to View in AngularJS在AngularJS中将变量从控制器传递到视图
【发布时间】:2016-11-11 09:16:40
【问题描述】:

我正在使用 Places 库和 angular google places autocomplete 模块。自动完成功能完美运行,点击时显示和选择结果。

我现在要做的是在用户选择自动完成的结果之一后从地址生成地图

我的控制器中有以下功能:

$scope.$on('g-places-autocomplete:select', function(event, place) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode( { "address": place.name }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK && results.length > 0) {
            location = results[0].geometry.location,
                lat      = location.lat(),
                lng      = location.lng();

            var latlng = new google.maps.LatLng(lat,lng);
            var myOptions = {
                zoom: 8,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        }
    });
});

它不起作用,我很确定这是因为它无法从前端访问 map_canvas 元素(它本身就在模板视图中)。

<div id="map_canvas" style="height:300px;"></div>

如何链接两者(或将 lat 和 lng 变量传递到前端)以在用户选择结果时显示地图?

编辑

我创建了一个Plunkr 来说明错误。你会看到,一旦你选择了一个位置,它就会重定向,在我的例子中是 http://localhost:9000/(1.650801,%2010.267894999999953),最后一部分是纬度和经度.

【问题讨论】:

  • 你有机会添加一个 plunkr 吗?如果我可以编辑一些代码,我很乐意看看...
  • @panzhuli 检查编辑!

标签: javascript angularjs google-maps autocomplete


【解决方案1】:

好的 - 我调整了一些东西,主要是为了清晰起见。我认为您在变量声明方面遇到了一些问题。现在加载一个地图对象。我会让你费尽心思让它显示数据:-)

(function(){

  var app = angular.module('wopWop', ['google.places']);

  app.controller('MainController', function($scope){
        $scope.$on('g-places-autocomplete:select', function(event, place) {
          var loc, lat, lng, latlng, map, options,
              geocoder = new google.maps.Geocoder();

          geocoder.geocode( { "address": place.name }, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK && results.length > 0) {
                    loc = results[0].geometry.location,
                    lat = loc.lat(),
                    lng = loc.lng();
                  }
            });
            latlng = new google.maps.LatLng(lat,lng);
            options = {
               zoom: 1,
               center: latlng,
               mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById("map_canvas"), options);
        });
  });
})();

Plunkr

【讨论】:

    猜你喜欢
    • 2014-10-19
    • 2012-02-10
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多