I want to display a specific result using the Google Maps API reverse geocoding. 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
(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
);
}
}
}
})();
<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. 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:
<div id='map'></div>
You can then also add markers, pop-up boxes etc to the map object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.