为谷歌地图集成搜索表单
Integrating Search Form for Google Maps
我正在使用Google Maps Javascript V3 API构建一个搜索表单。在执行搜索后,我下面的代码成功地通过了地理坐标,但地图没有更新。我尝试在initialize()中移动codeAddress函数,但搜索按钮不起作用。如何正确地将两者结合起来?
HTML:
<form>
<input type="text" name="address" id="address" />
<input type="button" class="search_button" value="" onclick="codeAddress()" />
</form>
JavaScript:
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
center: { lat: 48.509532, lng: -122.643852}
};
var map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
var locations = <?php echo json_encode($locations_array); ?>;
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
animation: google.maps.Animation.DROP,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
var content = '';
infowindow.setContent(content);
infowindow.open(map, marker);
}
})(marker, i));
}
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert(results[0].geometry.location);
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Please try again: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
您的主要问题是映射变量是initialize函数的本地变量,因此它在运行HTML点击函数的全局范围内不可用。
一个解决方案:
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
center: {
lat: 48.509532,
lng: -122.643852
},
zoom: 4
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
工作小提琴
另一个解决方案:
在initialize函数中定义codeAddress,并使用google.maps.event.addDomListener函数:
google.maps.event.addDomListener(document.getElementsByClassName('search_button')[0],'click',codeAddress);
工作小提琴
相关文章:
- 使用JS和jQuery搜索HTML表
- 使用PHP和JavaScript动态搜索SQL表并在HTML上显示
- 控制器作为搜索输入表单的语法
- 获取HTML表中单击的列中第一个单元格和单击的行中第一个单元的内容
- 基于ng表行单击更改uib选项卡集内容
- 复选框单击覆盖表行单击
- Jquery在表中单击时更改按钮的文本
- 如何在反应表中单击表行的列之一时获取表行的数据上下文
- 数据表 - 通过单击事件获取当前行的数据库 ID
- 如何使用 html 表单中的一个文本字段来搜索数据库表中的任何列
- 表行单击事件与链接
- JavaScript函数在Pageload上调用,而不是在动态生成的表中单击按钮时调用
- 通过传递 ID 搜索数据表中的数据
- 搜索 HTML 表并查找具有必填类的文本字段
- 在表行单击时停止 JS 事件传播
- 获取从动态表中单击的文本的值并传递给 Servelet
- 搜索条件表单和集合
- 最好的方式添加一个域名搜索ajax表单
- 在选择框发生变化时,重新搜索提交表单
- 编写脚本并搜索结果(表单)