从Google地图自动填充中检索信息 [英] Retrieve info from google maps autocomplete

查看:76
本文介绍了从Google地图自动填充中检索信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这段代码来生成带有自动完成功能的Google地图,并使用lat,lng,adress和town等信息进行自动填充。问题是我无法为城镇检索正确的值。



这是我的代码

 <!DOCTYPE html> 
< html>
< head>
< meta name =viewportcontent =initial-scale = 1.0,user-scalable = no>
< meta charset =utf-8>
< style>
html,body {
height:100%;
保证金:0;
padding:0;
}
#map {
height:100%;
}
.controls {
margin-top:10px;
border:1px透明;
border-radius:2px 0 0 2px;
box-sizing:border-box;
-moz-box-sizing:border-box;
height:32px;
概述:无;
box-shadow:0 2px 6px rgba(0,0,0,0.3);
}

#pac-input {
background-color:#fff;
font-family:Roboto;
font-size:15px;
font-weight:300;
margin-left:12px;
padding:0 11px 0 13px;
文本溢出:省略号;
width:300px;
}

#pac-input:focus {
border-color:#4d90fe;
}

.pac-container {
font-family:Roboto;
}

#type-selector {
color:#fff;
背景颜色:#4d90fe;
padding:5px 11px 0px 11px;
}

#类型选择器标签{
font-family:Roboto;
font-size:13px;
font-weight:300;
}

< / style>
< / head>
< body>
< input id =pac-inputclass =controlstype =text
placeholder =Enter a location>

< div id =mapstyle =width:500px; height:500px;>< / div>

< script>
函数initMap(){
var map = new google.maps.Map(document.getElementById('map'),{
center:{lat:-33.8688,lng:151.2195},
zoom:13
});
var options = {
componentRestrictions:{country:it}
};

var input = / ** @type {!HTMLInputElement} * /(
document.getElementById('pac-input'));

var autocomplete = new google.maps.places.Autocomplete(input,options);
autocomplete.bindTo('bounds',map);

var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map:map,
anchorPoint:new google.maps.Point(0,-29),
});

autocomplete.addListener('place_changed',function(){
infowindow.close();
marker.setVisible(false);
var place = autocomplete。 getPlace();

if(!place.geometry){
window.alert(Autocomplete返回的地方不包含几何图形);
return;
}

//如果地点有一个几何图形,那么将其显示在地图上
if(place.geometry.viewport){
map.fitBounds(place.geometry.viewport) ;
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); //为什么是17?因为它看起来不错。
}
marker.setIcon(/ ** @type {google.maps.Icon} * /({
url:place.icon,
size:new google.maps.Size(71,71) ,
origin:new google.maps.Point(0,0),
anchor:new google.maps.Point(17,34),
scaledSize:new google.maps.Size 35,35)
)));
marker.setPosition(place.geometry.location);
marker.setVisible(true);

var address =' ';
if(place.address_components){
地址= [
(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('');
}

infowindow.setContent('< div>< strong>'+ place.name +'< / strong>< br>'+ address);
infowindow.open(map,marker);



var adress_form = address;
document.getElementById('adress')。value = adress_form

var lat_form = place.geometry.location.lat();
document.getElementById('lat')。value = lat_form

var lng_form = place.geometry.location.lng();
document.getElementById('lng')。value = lng_form

函数extractFromAdress(components,type){
for(var i = 0; i< components.length; i ++ )
for(var j = 0; j< components [i] .types.length; j ++)
if(components [i] .types [j] ==类型)返回组件[i]。 LONG_NAME;
return;
}

var town = extractFromAdress(results [0] .address_components,locality);
document.getElementById('city')。value = town
});
}
< / script>
< form method =postaction =a.php>
< input placeholder =adresstype =textid =adressname =adress>
< input placeholder =citytype =textid =cityname =city>
< input placeholder =lattype =textid =latname =lat>
< input placeholder =lngtype =textid =lngname =lng>
< input placeholder =latlngtype =textid =latlngname =latlng>
< input placeholder =nametype =textid =namename =name>
< input type =submitvalue =inserisci>
< script src =https://maps.googleapis.com/maps/api/js?key=MYKEY&signed_in=true&libraries=places&callback=initMap
async defer><<<< ; /脚本>
< / form>
< / body>
< / html>


解决方案

c $ c>未捕获的ReferenceError:结果未定义在这一行上:

  var town = extractFromAdress (结果[0] .address_components,locality); 

这应该是您检索的地方对象(您从中获得了其他信息):

  var place = autocomplete.getPlace(); 

然后它就起作用了(如果结果有locality类型的结果)

  var town = extractFromAdress(place.address_components,locality); 
document.getElementById('city')。value = town;

概念证明小提琴



程式码片段:

 函数initMap(){var map = new google.maps.Map(document.getElementById('map'),{center:{lat:-33.8688,lng:151.2195},zoom:13 }); var options = {componentRestrictions:{country:it}}; var input = / ** @type {!HTMLInputElement} * /(document.getElementById('pac-input')); var autocomplete = new google.maps.places.Autocomplete(input,options); autocomplete.bindTo('bounds',map); var infowindow = new google.maps.InfoWindow(); var marker = new google.maps.Marker({map:map,anchorPoint:new google.maps.Point(0,-29),}); autocomplete.addListener('place_changed',function(){infowindow.close(); marker.setVisible(false); var place = autocomplete.getPlace(); if(!place.geometry){window.alert(Autocomplete's returned place包含没有几何);返回;} / /如果地方有一个几何,然后将其呈现在地图上if(place.geometry.viewport){map.fitBounds(place.geometry.viewport);} else {map。 setCenter(place.geometry.location); map.setZoom(17); //为什么是17?因为它看起来不错。} marker.setIcon(/ ** @type {google.maps.Icon} * /({url:place .icon,size:new google.maps.Size(71,71),origin:new google.maps.Point(0,0),anchor:new google.maps.Point(17,34),scaledSize:new google。 map.Size(35,35)})); marker.setPosition(place.geometry.location); marker.setVisible(true); var address =''; if(place.address_components){address = [(place.address_components [0]&& place.address_c omponents [0] .short_name || '),(place.address_components [1]& place.address_components [1] .short_name ||''),(place.address_components [2]& place.address_components [2] .short_name || '')] .join(''); } infowindow.setContent('< div>< strong>'+ place.name +'< / strong>< br>'+ address); infowindow.open(map,marker); var adress_form = address; document.getElementById('adress')。value = adress_form var lat_form = place.geometry.location.lat(); document.getElementById('lat')。value = lat_form var lng_form = place.geometry.location.lng();对于(var j = 0; j< components [i]),document.getElementById('lng').value = lng_form function extractFromAdress(components,type){for(var i = 0; i< components.length; i ++) .types.length; j ++)if(components [i] .types [j] == type)return components [i] .long_name;返回; } var town = extractFromAdress(place.address_components,locality); document.getElementById('city')。value = town; });} google.maps.event.addDomListener(window,'load',initMap);  

  html,body {height:100%;保证金:0; padding:0;}#map {height:100%;}。controls {margin-top:10px;边框:1px实心透明; border-radius:2px 0 0 2px;盒子尺寸:边框; -moz-box-sizing:border-box; height:32px;概要:无; box-shadow:0 2px 6px rgba(0,0,0,0.3);}#pac-input {background-color:#fff;字体家族:Roboto; font-size:15px; font-weight:300; margin-left:12px;填充:0 11px 0 13px;文本溢出:省略号;宽度:300px;}#pac-input:focus {border-color:#4d90fe;}。pac-container {font-family:Roboto;}#type-selector {color:#fff; background-color:#4d90fe; padding:5px 11px 0px 11px;}#type-selector label {font-family:Roboto; font-size:13px; font-weight:300;}  

< script src = https://maps.googleapis.com/maps/api/js?libraries=places\"></script><input id =pac-inputclass =controlstype =textplaceholder = Enter a location>< div id =mapstyle =width:500px; height:500px;>< / div>< form method =postaction =a.php> ; < input placeholder =adresstype =textid =adressname =adress> < input placeholder =citytype =textid =cityname =city> < input placeholder =lattype =textid =latname =lat> < input placeholder =lngtype =textid =lngname =lng> < input placeholder =latlngtype =textid =latlngname =latlng> < input placeholder =nametype =textid =namename =name> < input type =submitvalue =inserisci>< / form>

I've this code that I use to generate a google map with autocomplete e some field that will autofill with info like lat, lng, adress and town. The problem is that I cant archieve to retrieve the correct value for town.

Here is my code

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
  #map {
    height: 100%;
  }
.controls {
margin-top: 10px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}

#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 300px;
}

#pac-input:focus {
border-color: #4d90fe;
}

.pac-container {
font-family: Roboto;
 }

#type-selector {
color: #fff;
background-color: #4d90fe;
padding: 5px 11px 0px 11px;
}

#type-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}

</style>
</head>
<body>
<input id="pac-input" class="controls" type="text"
    placeholder="Enter a location">

<div id="map" style="width:500px; height:500px;"></div>

<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
var options = {
componentRestrictions: {country: "it"}
};

var input = /** @type {!HTMLInputElement} */(
  document.getElementById('pac-input'));

var autocomplete = new google.maps.places.Autocomplete(input, options);
autocomplete.bindTo('bounds', map);

var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29),
});

autocomplete.addListener('place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();

if (!place.geometry) {
  window.alert("Autocomplete's returned place contains no geometry");
  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.setIcon(/** @type {google.maps.Icon} */({
  url: place.icon,
  size: new google.maps.Size(71, 71),
  origin: new google.maps.Point(0, 0),
  anchor: new google.maps.Point(17, 34),
  scaledSize: new google.maps.Size(35, 35)
}));
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(' ');
}

infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);



var adress_form = address;
document.getElementById('adress').value = adress_form

var lat_form= place.geometry.location.lat();
document.getElementById('lat').value = lat_form

var lng_form= place.geometry.location.lng();
document.getElementById('lng').value = lng_form

function extractFromAdress(components, type){
for (var i=0; i<components.length; i++)
    for (var j=0; j<components[i].types.length; j++)
        if (components[i].types[j]==type) return components[i].long_name;
return "";
}

var town = extractFromAdress(results[0].address_components, "locality");
    document.getElementById('city').value = town
});
}
</script>
<form method="post" action="a.php">
<input placeholder="adress" type="text" id="adress" name="adress">
<input placeholder="city" type="text" id="city" name="city">
<input placeholder="lat" type="text" id="lat" name="lat">
<input placeholder="lng" type="text" id="lng" name="lng">
<input placeholder="latlng" type="text" id="latlng" name="latlng">
<input placeholder="name" type="text" id="name" name="name">
<input type="submit" value="inserisci">
<script src="https://maps.googleapis.com/maps/api/js?key=MYKEY&signed_in=true&libraries=places&callback=initMap"
    async defer></script>
    </form>
</body>
</html>

解决方案

I get a javascript error with your code: Uncaught ReferenceError: results is not defined on this line:

var town = extractFromAdress(results[0].address_components, "locality");

That should be the place object you retrieved (that you got the rest of the information from):

var place = autocomplete.getPlace();

Then it works (if the result has a result of type "locality")

var town = extractFromAdress(place.address_components, "locality");
document.getElementById('city').value = town;

proof of concept fiddle

code snippet:

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: -33.8688,
      lng: 151.2195
    },
    zoom: 13
  });
  var options = {
    componentRestrictions: {
      country: "it"
    }
  };

  var input = /** @type {!HTMLInputElement} */ (
    document.getElementById('pac-input'));

  var autocomplete = new google.maps.places.Autocomplete(input, options);
  autocomplete.bindTo('bounds', map);

  var infowindow = new google.maps.InfoWindow();
  var marker = new google.maps.Marker({
    map: map,
    anchorPoint: new google.maps.Point(0, -29),
  });

  autocomplete.addListener('place_changed', function() {
    infowindow.close();
    marker.setVisible(false);
    var place = autocomplete.getPlace();

    if (!place.geometry) {
      window.alert("Autocomplete's returned place contains no geometry");
      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.setIcon( /** @type {google.maps.Icon} */ ({
      url: place.icon,
      size: new google.maps.Size(71, 71),
      origin: new google.maps.Point(0, 0),
      anchor: new google.maps.Point(17, 34),
      scaledSize: new google.maps.Size(35, 35)
    }));
    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(' ');
    }

    infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
    infowindow.open(map, marker);

    var adress_form = address;
    document.getElementById('adress').value = adress_form

    var lat_form = place.geometry.location.lat();
    document.getElementById('lat').value = lat_form

    var lng_form = place.geometry.location.lng();
    document.getElementById('lng').value = lng_form

    function extractFromAdress(components, type) {
      for (var i = 0; i < components.length; i++)
        for (var j = 0; j < components[i].types.length; j++)
          if (components[i].types[j] == type) return components[i].long_name;
      return "";
    }

    var town = extractFromAdress(place.address_components, "locality");
    document.getElementById('city').value = town;
  });
}
google.maps.event.addDomListener(window, 'load', initMap);

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 100%;
}
.controls {
  margin-top: 10px;
  border: 1px solid transparent;
  border-radius: 2px 0 0 2px;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  height: 32px;
  outline: none;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#pac-input {
  background-color: #fff;
  font-family: Roboto;
  font-size: 15px;
  font-weight: 300;
  margin-left: 12px;
  padding: 0 11px 0 13px;
  text-overflow: ellipsis;
  width: 300px;
}
#pac-input:focus {
  border-color: #4d90fe;
}
.pac-container {
  font-family: Roboto;
}
#type-selector {
  color: #fff;
  background-color: #4d90fe;
  padding: 5px 11px 0px 11px;
}
#type-selector label {
  font-family: Roboto;
  font-size: 13px;
  font-weight: 300;
}

<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<input id="pac-input" class="controls" type="text" placeholder="Enter a location">

<div id="map" style="width:500px; height:500px;"></div>
<form method="post" action="a.php">
  <input placeholder="adress" type="text" id="adress" name="adress">
  <input placeholder="city" type="text" id="city" name="city">
  <input placeholder="lat" type="text" id="lat" name="lat">
  <input placeholder="lng" type="text" id="lng" name="lng">
  <input placeholder="latlng" type="text" id="latlng" name="latlng">
  <input placeholder="name" type="text" id="name" name="name">
  <input type="submit" value="inserisci">
</form>

这篇关于从Google地图自动填充中检索信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆