Google地图搜索功能如何在我的自定义按钮点击(没有自动填充)搜索时触发?我已经有了这段代码...... 。
This example使用Google地方自动填充功能向地图添加搜索框。
人们可以输入地理搜索。
搜索框将返回一个包含多个地点和预测搜索字词的选择列表。
答案 0 :(得分:0)
这是我的样本, 我正在使用文本框的“更改”事件和按钮的“单击”事件
var map;
var root;
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': 'Ha noi, Vietnam'}, function(results, status) {
root = results[0].geometry.location;
map = new google.maps.Map(document.getElementById('map'), {
zoom: 18,
center: root,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var center = {latLng: root, style: 'ae', content: 'md'};
var zoomControlDiv = document.createElement('div');
var zoomControl = new ZoomControl(zoomControlDiv, map);
zoomControlDiv.index = 1;
map.controls[google.maps.ControlPosition.TOP_LEFT].push(zoomControlDiv);
});
}
function ZoomControl(controlDiv, map) {
// Creating divs & styles for custom zoom control
controlDiv.style.padding = '5px';
// Set CSS for the control wrapper
var controlWrapper = document.createElement('div');
controlDiv.appendChild(controlWrapper);
// Set CSS for the zoomIn
var txtAddress = document.createElement('input');
//zoomInButton.innerHTML = '<br><img src=images/Plus.png title="Zoom In">';
txtAddress.type="text";
controlWrapper.appendChild(txtAddress);
var bttAddress = document.createElement('input');
//zoomInButton.innerHTML = '<br><img src=images/Plus.png title="Zoom In">';
bttAddress.type = "button";
bttAddress.value= "Search";
controlWrapper.appendChild(txtAddress);
controlWrapper.appendChild(bttAddress);
google.maps.event.addDomListener(txtAddress, 'change', function() {
geocoder.geocode({'address': txtAddress.value}, function(results, status) {
if (status === 'OK') {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: txtAddress.value+' '+results[0].geometry.location
});
map.setCenter(results[0].geometry.location);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
});
google.maps.event.addDomListener(bttAddress, 'click', function() {
geocoder.geocode({'address': txtAddress.value}, function(results, status) {
if (status === 'OK') {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: txtAddress.value+' '+results[0].geometry.location
});
map.setCenter(results[0].geometry.location);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
<!DOCTYPE HTML>
<html>
<head>
<title>Google Maps API</title>
<style type="text/css">
#map {
width: 100%;
height: 600px;
}
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script type="text/javascript" src="init_map.js"></script>
</head>
<body>
<div id="map">
</div>
</body>
</html>