这是我的地理编码器谷歌地图代码 当我更改选择选项时,我的代码有效 当我选择多个地方时,标记会添加到地图中 我想删除以前的标记。
<!DOCTYPE html>
<html><head><meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8"><title>Geocoding service</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var geocoder;var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(9.9252007,78.1197754);
var mapOptions = {
zoom: 8,center: latlng
} map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map, position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}}); }
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head><body>
<div align="center" verticle-align="ce">
<form method="get" action="">
<select name="address" id="address" onChange="codeAddress()" >
<option value="chennai,india">chennai,india</option>
<option value="madurai,india">madurai,india</option>
<option value="bangalore,india">bangalore,india</option>
<option value="delhi,india">Delhi</option>
</select>
</form> </div>
<div id="map-canvas" style="width:750px;height:500px;"></div>
</body></html>
代码的工作: 当我加载页面时,它自动加载初始位置,我更改选项值,它将加载选择一个。
答案 0 :(得分:0)
将marker
设为全局变量,将标记定义移至initialize()
函数,并使用marker.setPosition()
更改选择集位置:
var geocoder;
var map;
var marker;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(9.9252007,78.1197754);
var mapOptions = {
zoom: 8,
center: latlng
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
marker = new google.maps.Marker({
map: map
});
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var position = results[0].geometry.location;
map.setCenter(position);
marker.setPosition(position);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
请参阅example at jsbin。