我正在使用 Places 库和 angular google places autocomplete模块。自动完成功能运行良好,结果将在单击时显示和选择。
我现在想做的是一旦用户选择自动完成的结果之一,就从地址生成 map 。
我的 Controller 中有以下功能:
$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 元素(它本身位于模板 View 内)。
<div id="map_canvas" style="height:300px;"></div>
如何链接两者(或将 lat 和 lng 变量传递到前端)以使用户选择结果时显示 map ?
编辑
我做了一个Plunkr这说明了错误。您会看到,一旦您选择了一个位置,它就会进行重定向,在我的例子中,重定向到 http://localhost:9000/(1.650801,%2010.267894999999953),这是纬度和经度的最后一部分.
最佳答案
好的 - 我调整了一些内容,为了清晰起见,主要是风格上的调整。我认为您在变量声明方面遇到了一些问题。现在加载一个 map 对象。我会让你胡乱让它显示数据:-)
(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);
});
});
})();
关于javascript - 在 AngularJS 中将变量从 Controller 传递到 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38272822/