huj*_*h14 11 google-maps autocomplete meteor
因此,我尝试将https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform的搜索栏添加到我的Meteor应用.首先,我需要加载Google商家信息库.但是,该链接还尝试直接写入DOM以获取另一个链接.Meteor不允许这样,所以我决定像这样加载两个js文件.
Template.listingSubmit.rendered = function(){
if (!this.rendered){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places";
document.body.appendChild(script);
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://maps.gstatic.com/cat_js/maps-api-v3/api/js/17/13/%7Bmain,places%7D.js";
document.body.appendChild(script);
this.rendered = true;
}
};
Run Code Online (Sandbox Code Playgroud)
那样有用吗?我的下一个问题是如何初始化自动填充文本字段?相应模板中的html很简单.
<div id="locationField">
<input id="autocomplete" placeholder="Enter your address" type="text">
</div>
Run Code Online (Sandbox Code Playgroud)
现在我尝试添加
var autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')),{types: ['geocode'] }
);
Run Code Online (Sandbox Code Playgroud)
到Template.listingSubmit.rendered但没有任何反应.我得到了谷歌未定义的错误.什么地方出了错?
我一直在处理同样的问题,只是遇到了一个解决方案.这就是我做的.
首先,将以下包添加到项目中:
`mrt add googlemaps`
Run Code Online (Sandbox Code Playgroud)
或者,如果你使用meteor> = 0.9:
meteor add mrt:googlemaps
Run Code Online (Sandbox Code Playgroud)
接下来,创建以下文件:/client/lib/googlePlaces.js
将以下代码放在此js文件中:
GoogleMaps.init({
'sensor': false, //optional
'key': 'your api key here!', //optional
'language': 'en', //optional
'libraries': 'places'
});
Run Code Online (Sandbox Code Playgroud)
显然用你的密钥替换api密钥!此代码将启动对google api的调用,并将places脚本下载到客户端.
现在,回答有关如何使自动完成工作的问题.你的HTML和js看起来很好,除了一件事.你需要将你的js包装在window.onload函数中,以便它等待下载google api脚本!
HTML
<div id="locationField">
<input id="autocomplete" placeholder="Enter your address" type="text">
</div>
Run Code Online (Sandbox Code Playgroud)
JS
window.onload = function() {
var autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')),{types: ['geocode'] }
);
};
Run Code Online (Sandbox Code Playgroud)
我没有测试过您的HTML/JS,但它看起来与我的非常相似.
以为我会分享最终为我工作的东西
包裹保持不变,但是js改变了:
Template.myTemplateName.rendered = function () {
window.onload = function() {
input = document.getElementById('autocomplete');
autocomplete = new google.maps.places.Autocomplete(input);
// When the user selects an address from the dropdown,
google.maps.event.addListener(autocomplete, 'place_changed', function() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
console.log("place: " + JSON.stringify(place) );
});
};
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3946 次 |
| 最近记录: |