繁体   English   中英

从自动完成地址输入中获取经纬度,并使用Google Maps API在下面显示地图

[英]Get Lat and Long from autocomplete address input and show the map below with google maps API

我有一个输入字段,用于输入支持Google Maps API中位置建议的位置。 纬度和经度还有两个输入字段。 最后一个div用于显示输入位置上方的地图。 每当有人开始输入位置并从建议中选择一个位置时,该位置的地图就会自动显示在下面的div中。 所有这些都应该是实时的。

到目前为止,我已经写了以下内容-

<input type="text" name="address1" id="address1" class="form-control" required="required" onkeyup="findAddress()" />
<input type="text" name="lattitude" id="cityLat" placeholder="Lattitude" class="form-control" required="required"/>
<input type="text" name="longitude" id="cityLng" placeholder="Longitude" class="form-control" required="required"/>

<div id="showMap"></div>

而JavaScript是

function findAddress() {

var input = document.getElementById('address1');
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
            var place = autocomplete.getPlace();
            document.getElementById('cityLat').value = place.geometry.location.lat();
            document.getElementById('cityLng').value = place.geometry.location.lng();
}

我已经包含了maps API

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>

搜索建议有效,但其余无效。

不知道是什么原因引起的,但是您的JavaScript包含语法错误。 你有这个:

function findAddress() {

var input = document.getElementById('address1');
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
            var place = autocomplete.getPlace();
            document.getElementById('cityLat').value = place.geometry.location.lat();
            document.getElementById('cityLng').value = place.geometry.location.lng();
}

但是您没有正确关闭addListener 正确的格式应为:

function findAddress() {

var input = document.getElementById('address1');
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
            var place = autocomplete.getPlace();
            document.getElementById('cityLat').value = place.geometry.location.lat();
            document.getElementById('cityLng').value = place.geometry.location.lng();
});
}

注意}); 在倒数第二行。

在您的脚本中找到以下代码:

if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
}

在这

“ window.alert(” Locaton:'“ + place.geometry.location +”'“);”

在“如果”条件下,添加以下行,它将提醒/通知多时且延迟选项/地址选择:

您的代码将如下所示:

if (place.geometry.viewport) {
window.alert("Locaton: '" + place.geometry.location + "'"); //Add this line
map.fitBounds(place.geometry.viewport);
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM