Javascript 如何从Google Maps API中的拖动事件中获取自动完成地址?
我创建了一个谷歌地理编码器,我想能够拿起自动完成的地址标记时,被拖动或点击 这里的问题是,当搜索地址时,没有问题,它显示准确的位置,并提供自动完成的地址,如街道地址、城市、州、邮政编码、国家等 问题是,当将pin点从一个位置拖到另一个位置时,整个地址会根据google pin位置发生变化,但不会给出地址子部分,如街道地址、城市、州、邮政编码、国家(不更新意味着只有在那里才有旧的搜索值) 霉菌代码:Javascript 如何从Google Maps API中的拖动事件中获取自动完成地址?,javascript,jquery,html,google-maps,Javascript,Jquery,Html,Google Maps,我创建了一个谷歌地理编码器,我想能够拿起自动完成的地址标记时,被拖动或点击 这里的问题是,当搜索地址时,没有问题,它显示准确的位置,并提供自动完成的地址,如街道地址、城市、州、邮政编码、国家等 问题是,当将pin点从一个位置拖到另一个位置时,整个地址会根据google pin位置发生变化,但不会给出地址子部分,如街道地址、城市、州、邮政编码、国家(不更新意味着只有在那里才有旧的搜索值) 霉菌代码: <head> <title>Place Autocomplete Add
<head>
<title>Place Autocomplete Address Form</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#locationField, #controls {
position: relative;
width: 480px;
}
#autocomplete {
position: absolute;
top: 0px;
left: 0px;
width: 99%;
}
.label {
text-align: right;
font-weight: bold;
width: 100px;
color: #303030;
}
#address {
border: 1px solid #000090;
background-color: #f0f0ff;
width: 480px;
padding-right: 2px;
}
#address td {
font-size: 10pt;
}
.field {
width: 99%;
}
.slimField {
width: 80px;
}
.wideField {
width: 200px;
}
#locationField {
height: 20px;
margin-bottom: 2px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA1BvEkX8v91LRu43HQe0-GNaHTVnoTSQs&libraries=places&callback=initMap"
async defer></script>
</head>
<body>
<br><br>
<div id="locationField">
<input id="autocomplete" placeholder="Enter your address" type="text"></input>
</div>
<table id="address">
<tr>
<td class="label">Street address</td>
<td class="slimField"><input class="field" id="street_number"
disabled="true" name="streetnumber"></input></td>
<td class="wideField" colspan="2"><input class="field" id="route"
disabled="true" name="route"></input></td>
</tr>
<tr>
<td class="label">City</td>
<!-- Note: Selection of address components in this example is typical.
You may need to adjust it for the locations relevant to your app. See
https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform
-->
<td class="wideField" colspan="3"><input class="field" id="locality"
disabled="true" name="locality"></input></td>
</tr>
<tr>
<td class="label">State</td>
<td class="slimField"><input class="field"
id="administrative_area_level_1" disabled="true" name="state" ></input></td>
<td class="label">Zip code</td>
<td class="wideField"><input class="field" id="postal_code"
disabled="true" name="postal_code"></input></td>
</tr>
<tr>
<td class="label">Country</td>
<td class="wideField" colspan="3"><input class="field"
id="country" disabled="true" name="country"></input></td>
</tr>
</table>
<div id="map" style="width: 50%; height: 250px;"></div>
<div id="infowindow-content">
<img src="" width="16" height="16" id="place-icon">
<span id="place-name" class="title"></span><br>
<span id="place-address"></span>
</div>
<script>
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};
var input = document.getElementById('autocomplete');
function initMap() {
var geocoder;
var autocomplete;
geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
var card = document.getElementById('locationField');
autocomplete = new google.maps.places.Autocomplete(input);
// Bind the map's bounds (viewport) property to the autocomplete object,
// so that the autocomplete requests use the current map bounds for the
// bounds option in the request.
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var infowindowContent = document.getElementById('infowindow-content');
infowindow.setContent(infowindowContent);
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29),
draggable: true
});
autocomplete.addListener('place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
console.log(place);
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert("No details available for input: '" + place.name + "'");
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindowContent.children['place-icon'].src = place.icon;
infowindowContent.children['place-name'].textContent = place.name;
infowindowContent.children['place-address'].textContent = address;
infowindow.open(map, marker);
fillInAddress();
});
function fillInAddress() {
var place = autocomplete.getPlace(input);
console.log(place);
for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
}
google.maps.event.addListener(marker, 'dragend', function() {
geocoder.geocode({'latLng': marker.getPosition()}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
console.log(autocomplete);
$('#autocomplete').val(results[0].formatted_address);
google.maps.event.trigger(autocomplete, 'place_changed');
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
}
);
}
</script>
</body>
</html>
放置自动完成的地址表单
/*始终明确设置贴图高度以定义div的大小
*包含映射的元素*/
#地图{
身高:100%;
}
/*可选:使示例页面填充窗口*/
html,正文{
身高:100%;
保证金:0;
填充:0;
}
#位置字段,#控件{
位置:相对位置;
宽度:480px;
}
#自动完成{
位置:绝对位置;
顶部:0px;
左:0px;
宽度:99%;
}
.标签{
文本对齐:右对齐;
字体大小:粗体;
宽度:100px;
颜色:303030;
}
#地址{
边框:1px实心#000090;
背景色:#f0ff;
宽度:480px;
右侧填充:2px;
}
#地址:td{
字号:10pt;
}
.场{
宽度:99%;
}
斯莱姆菲尔德先生{
宽度:80px;
}
.威德菲尔德{
宽度:200px;
}
#位置场{
高度:20px;
边缘底部:2px;
}
街道地址
城市
陈述
邮政编码
国家
变量组件形式={
街道编号:“短名称”,
路线:'long_name',
地点:'long_name',
行政区域级别1:“短名称”,
国家:'long_name',
邮政编码:“短名称”
};
var input=document.getElementById('autocomplete');
函数initMap(){
var地理编码器;
var自动完成;
geocoder=新的google.maps.geocoder();
var map=new google.maps.map(document.getElementById('map'){
中心:{lat:-33.8688,lng:151.2195},
缩放:13
});
var card=document.getElementById('locationField');
autocomplete=newgoogle.maps.places.autocomplete(输入);
//将贴图的边界(视口)属性绑定到自动完成对象,
//因此,自动完成请求使用
//请求中的边界选项。
autocomplete.bindTo('bounds',map);
var infowindow=new google.maps.infowindow();
var infowindowContent=document.getElementById('infowindow-content');
setContent(infowindowContent);
var marker=new google.maps.marker({
地图:地图,
主播点:新google.maps.Point(0,-29),
德拉格布尔:是的
});
autocomplete.addListener('place\u changed',function(){
infowindow.close();
marker.setVisible(假);
var place=autocomplete.getPlace();
控制台日志(位置);
如果(!place.geometry){
//用户输入了未建议的地点的名称,然后
//按Enter键,或Place Details请求失败。
window.alert(“没有可供输入的详细信息:“+place.name+””);
返回;
}
//如果该地点有几何图形,则将其显示在地图上。
if(place.geometry.viewport){
map.fitBounds(place.geometry.viewport);
}否则{
地图。设置中心(地点。几何。位置);
map.setZoom(17);//为什么是17?因为它看起来不错。
}
标记器.设置位置(位置.几何.位置);
marker.setVisible(true);
var地址=“”;
if(位置、地址和组件){
地址=[
(place.address_components[0]&&place.address_components[0]。简称| | |“”),
(place.address_components[1]&&place.address_components[1]。简称| | |“”),
(place.address_components[2]&&place.address_components[2]。简称| |“”)
].加入(“”);
}
infowindowContent.children['place-icon'].src=place.icon;
infowindowContent.children['place-name'].textContent=place.name;
infowindowContent.children['place-address'].textContent=地址;
信息窗口。打开(地图、标记);
fillInAddress();
});
函数fillInAddress(){
var place=autocomplete.getPlace(输入);
控制台日志(位置);
for(componentForm中的var组件){
document.getElementById(组件).value='';
document.getElementById(组件).disabled=false;
}
对于(变量i=0;i
我需要在这里根据拖动的位置它应该改变自动完成地址也,帮助我任何人。提前感谢…是的,您的函数fillInAddress()。我将其更改为,以便您可以直接将地址组件作为参数提供给它
function fillInAddress(new_address) { // optional parameter
if(typeof new_address == 'undefined') {
var place = autocomplete.getPlace(input);
}
else {
place = new_address;
}
...
}
所以
google.maps.event.addListener(marker, 'dragend', function() {
...
// do not trigger place_changed. Instead call this:
fillInAddress(results[0]);
...
})
完整代码
<html>
<head>
<title>Place Autocomplete Address Form</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
<style>
/* Always set the map height explicitly to define the size of the div
element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#locationField,
#controls {
position: relative;
width: 480px;
}
#autocomplete {
position: absolute;
top: 0px;
left: 0px;
width: 99%;
}
.label {
text-align: right;
font-weight: bold;
width: 100px;
color: #303030;
}
#address {
border: 1px solid #000090;
background-color: #f0f0ff;
width: 480px;
padding-right: 2px;
}
#address td {
font-size: 10pt;
}
.field {
width: 99%;
}
.slimField {
width: 80px;
}
.wideField {
width: 200px;
}
#locationField {
height: 20px;
margin-bottom: 2px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA1BvEkX8v91LRu43HQe0-GNaHTVnoTSQs&libraries=places&callback=initMap" async defer></script>
</head>
<body>
<br><br>
<div id="locationField">
<input id="autocomplete" placeholder="Enter your address" type="text"></input>
</div>
<table id="address">
<tr>
<td class="label">Street address</td>
<td class="slimField"><input class="field" id="street_number" disabled="true" name="streetnumber"></input>
</td>
<td class="wideField" colspan="2"><input class="field" id="route" disabled="true" name="route"></input>
</td>
</tr>
<tr>
<td class="label">City</td>
<!-- Note: Selection of address components in this example is typical.
You may need to adjust it for the locations relevant to your app. See
https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform
-->
<td class="wideField" colspan="3"><input class="field" id="locality" disabled="true" name="locality"></input>
</td>
</tr>
<tr>
<td class="label">State</td>
<td class="slimField"><input class="field" id="administrative_area_level_1" disabled="true" name="state"></input>
</td>
<td class="label">Zip code</td>
<td class="wideField"><input class="field" id="postal_code" disabled="true" name="postal_code"></input>
</td>
</tr>
<tr>
<td class="label">Country</td>
<td class="wideField" colspan="3"><input class="field" id="country" disabled="true" name="country"></input>
</td>
</tr>
</table>
<div id="map" style="width: 50%; height: 250px;"></div>
<div id="infowindow-content">
<img src="" width="16" height="16" id="place-icon">
<span id="place-name" class="title"></span><br>
<span id="place-address"></span>
</div>
<script>
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};
var input = document.getElementById('autocomplete');
function initMap() {
var geocoder;
var autocomplete;
geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -33.8688,
lng: 151.2195
},
zoom: 13
});
var card = document.getElementById('locationField');
autocomplete = new google.maps.places.Autocomplete(input);
// Bind the map's bounds (viewport) property to the autocomplete object,
// so that the autocomplete requests use the current map bounds for the
// bounds option in the request.
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var infowindowContent = document.getElementById('infowindow-content');
infowindow.setContent(infowindowContent);
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29),
draggable: true
});
autocomplete.addListener('place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
console.log(place);
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert("No details available for input: '" + place.name + "'");
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindowContent.children['place-icon'].src = place.icon;
infowindowContent.children['place-name'].textContent = place.name;
infowindowContent.children['place-address'].textContent = address;
infowindow.open(map, marker);
fillInAddress();
});
function fillInAddress(new_address) { // optional parameter
if (typeof new_address == 'undefined') {
var place = autocomplete.getPlace(input);
} else {
place = new_address;
}
//console.log(place);
for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
}
google.maps.event.addListener(marker, 'dragend', function() {
geocoder.geocode({
'latLng': marker.getPosition()
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
console.log(autocomplete);
$('#autocomplete').val(results[0].formatted_address);
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
// google.maps.event.trigger(autocomplete, 'place_changed');
fillInAddress(results[0]);
}
}
});
});
}
</script>
</body>
</html>
放置自动完成的地址表单