[英]How to display the desired elements from Google Maps API reverse geocoding?
I want to display a specific result using the Google Maps API reverse geocoding. 我想使用Google Maps API反向地理编码显示特定结果。 I'm pulling in what I want in the console, but I'm blanking on pulling it in the display.
我要在控制台中输入想要的内容,但是在将其显示在显示屏中时却空白。
In addition, I can't get the form field to populate with the data. 另外,我无法获取表单字段来填充数据。 It populates in the
它填充在
tag, but doesn't go into the form 标记,但不进入表格
Codepen: https://codepen.io/Strawmr/pen/yLBXZVR Codepen: https ://codepen.io/Strawmr/pen/yLBXZVR
JS
JS
(function() {
var geocoder = new google.maps.Geocoder(),
locElement = document.querySelector("#loc"),
google_coords;
navigator.geolocation.getCurrentPosition(function(e) {
google_coords = new google.maps.LatLng(
e.coords.latitude,
e.coords.longitude // current address
);
geocoder.geocode({ latLng: google_coords },
reverseGeocoderSuccess);
});
function reverseGeocoderSuccess(results, status) {
var address;
if (status === google.maps.GeocoderStatus.OK) {
if (results[0]) {
var address_components =
results[0].address_components;
address = results[0].formatted_address;
locElement.innerHTML = address;
// print desired result to the console:
console.log(
address_components[3].short_name + ", " +address_components[5].short_name + " " + address_components[7].long_name + ", " + address_components[6].long_name
);
}
}
}
})();
HTML
的HTML
<div class="container-fluid">
<form class="form-horizontal" role="form">
<fieldset class="address">
<legend>Address</legend>
<div class="form-group">
<label class="control-label col-sm-2 col-md-3">
Location
</label>
<div class="col-sm-4 col-md-3">
<input class="form-control" type="text" id="loc" name="Location" value="" autocomplete="address-level2">
</div>
</div>
</fieldset>
</form>
To have the result appear in the form input box you can replace 要使结果显示在表单输入框中,您可以替换
locElement.innerHTML = address;
with 与
document.getElementById("loc").value = address;
To display a Google Map with the location (which I think is what you're trying to do) you will have to create a Map object and give it a center of your address coordinates. 要显示具有该位置的Google Map(我认为这是您要尝试的操作),您必须创建一个Map对象,并为其提供地址坐标的中心。 Something like:
就像是:
const map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: results[0].geometry.location.lat(),
lng: results[0].geometry.location.lng()
},
zoom: 8,
});
For the above to work you will also need to add a div to your HTML with id of map: 为了使上述方法起作用,您还需要在HTML中添加一个ID为map的div:
<div id='map'></div>
You can then also add markers, pop-up boxes etc to the map object. 然后,您还可以将标记,弹出框等添加到地图对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.