我正在使用以下 Google Places 脚本来获取用户的位置。我已经获得了完整的地址,但我需要解析结果以获取城市和国家。
我尝试了下面的脚本,但是并不总是有效,因为在某些情况下地址格式是不同的。
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Google Places Autocomplete textbox using google maps api</title>
</head>
<body>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.js"></script>
<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
var autocomplete = new google.maps.places.Autocomplete(document.getElementById('txtAutocomplete'));
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
var location = "<b>Address</b>: " + place.formatted_address + "<br/>";
location += "<b>Latitude</b>: " + place.geometry.location.lat() + "<br/>";
location += "<b>Longitude</b>: " + place.geometry.location.lng();
document.getElementById('lblResult').innerHTML = location;
});
}
</script>
<span>Location:</span>
<input type="text" id="txtAutocomplete" style="width: 300px" placeholder="Enter your address" /><br /><br />
<label id="lblResult" />
</body>
</html>
我尝试了下面的脚本,但是并不总是有效,因为在某些情况下地址格式是不同的。
var city = place.address_components[0] && place.address_components[0].short_name || '';
document.getElementById('lblResult').innerHTML = location;
console.log(city);