1
我的目標是具有自動完成功能的幾個輸入字段,每個輸入將在地圖上生成一個標記。然後我需要放大地圖以包含所有的標記。我部分工作,沒有自動完成功能。我曾嘗試將Google Maps API Places自動完成代碼添加到我的for循環中,但無濟於事。它爲所有輸入字段提供自動完成功能,但只爲最後一個輸入放置一個標記。自動完成生成多個標記
任何幫助/見解/指導表示讚賞。
這是我的代碼,自動完成功能目前被刪除,因爲我無法啓動它。
<div class="container-fluid">
<div class="row-fluid">
<div class="span4 well">
<div id="locations">
<form>
<label>Location 0</label>
<input id="address0" type="text" size="50" >
<button id="clearField0">Clear</button>
<div class="panel">
<label>Location 1</label>
<input id="address1" type="text" size="50">
<button id="clearField0">Clear</button>
</div>
<div class="panel">
<label>Location 2</label>
<input id="address2" type="text" size="50">
<button id="clearField0">Clear</button>
</div>
</form>
</div>
<button id="addField">+</button>
<button id="deleteField">-</button>
<button id="submit">Submit form</button>
</div>
<div class="span8">
<div id="map-wrapper">
<div id="google-map"></div>
</div>
</div>
</div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCtNo_o0u8wYeqgiFF-KpvAtEy18T-PvAo&sensor=false&callback=createMap"></script>
<script type="text/javascript">
var inputFields = parseInt($('form input').size());
var markers = [];
var createMap = function() {
var latlngbounds = new google.maps.LatLngBounds();
var geocoder = new google.maps.Geocoder();
var myOptions = {
center : new google.maps.LatLng(35.9081, -78.8628), //center to RTP
zoom : 12,
zoomControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map(document.getElementById("google-map"), myOptions);
$("#submit").on("click", function() {
setAllMap(null);
markers.pop();
for (i=0; i<inputFields; i++) {
var location = $("#address" + i).val();
geocoder.geocode({'address': location}, 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
});
latlngbounds.extend(results[0].geometry.location);
map.fitBounds(latlngbounds);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
};
});
function setAllMap(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
$('#addField').click(function(){ //add input field to bottom of form
$('form').append('<div class="panel"><label>Location '+ inputFields +'</label><input id="address'+ inputFields +'" type="text" size="50"><button id="clearField'+ inputFields +'">Clear</button></div>');
inputFields++;
});
$('#deleteField').click(function(){ //delete last input field
$('.panel').last().remove();
inputFields--;
});
};
</script>
你應該發佈你如何嘗試創建Autocomplete(目前還不清楚你嘗試實現哪種自動完成.... google.maps.places,jquery-ui?)當你嘗試使用google.maps .places.Autocomplete目前會因代碼失敗,因爲您忘記了加載場所庫,但是當加載場所庫並且自動完成已經按照預期應用於3輸入的meworks代碼時(它也會沒有自動完成) –
感謝您對Dr.Molle的評論,我能夠弄明白。我包括了地方圖書館(我在發佈之前必須意外刪除),並從地點自動填充示例頁面中刪除了我包括的內容:[link](https://developers.google.com/maps/documentation/javascript/例子/地方-自動完成)。感謝您的快速回復! – user2626924