Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

javascript - Retrieve info from google maps autocomplete

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...