0

I'm trying to save latitude and longitude by autocomplete Google Maps, but I can't make this work. I don't know how to use Google Maps Api. I need to add 2 fields with longitude and latitude, and when I select my address from my input, these 2 fields ( longitude and latitude ) should be filled with the correct values.

What I have tried so far:

Google map api get Latitude and longitude from autocomplete without map

Here is my script

<script>
    // This sample uses the Autocomplete widget to help the user select a
// place, then it retrieves the address components associated with that
// place, and then it populates the form fields with those details.
// This sample requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script
// src="https://maps.googleapis.com/maps/api/js?key=MY_API&libraries=places">

var placeSearch, autocomplete;

var componentForm = {
  street_number: 'short_name',
  route: 'long_name',
  locality: 'long_name',
  administrative_area_level_1: 'short_name',
  country: 'long_name',
  postal_code: 'short_name'
};

function initAutocomplete() {
  // Create the autocomplete object, restricting the search predictions to
  // geographical location types.
  autocomplete = new google.maps.places.Autocomplete(
      document.getElementById('autocomplete'), {types: ['geocode']});

  // Avoid paying for data that you don't need by restricting the set of
  // place fields that are returned to just the address components.
  autocomplete.setFields(['address_component']);

  // When the user selects an address from the drop-down, populate the
  // address fields in the form.
  autocomplete.addListener('place_changed', fillInAddress);
}

function fillInAddress() {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();

  for (var component in componentForm) {
    document.getElementById(component).value = '';
    document.getElementById(component).disabled = false;
  }

  // Get each component of the address from the place details,
  // and then fill-in the corresponding field on the form.
  for (var i = 0; i < place.address_components.length; i++) {
    var addressType = place.address_components[i].types[0];
    if (componentForm[addressType]) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType).value = val;
    }
  }
}



// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var geolocation = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      var circle = new google.maps.Circle(
          {center: geolocation, radius: position.coords.accuracy});
      autocomplete.setBounds(circle.getBounds());
    });
  }
}

    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=MY_API&libraries=places&callback=initAutocomplete"
        async defer></script>



Here is my view

 <div class="form-group col-md-4" style="left: 10px;position: relative" id="locationField">
                                      <label class="label" for="jobs">
                                      Address
                                      </label>
                                      <div class="input-group">
                                       <div class="input-group-addon" style="border-color: #bbb">
                                        <i class="icon-hotel-restaurant-235 u-line-icon-pro"></i>
                                       </div>
                                        <label class="input" style="height: 28px">
                                  <input id="autocomplete"
             placeholder="Enter your address"
             onFocus="geolocate()"
             type="text"
             style="height: 33px"
             name="address"/>                           </label>
    </div>
                                    </div>
Martin Schmelzer
  • 23,283
  • 6
  • 73
  • 98
Andrei Mihail
  • 29
  • 1
  • 6

2 Answers2

0

I have written this script for one of my recent project this works fine for me

<script>
var autocomplete;
function initAutocomplete(){
    autocomplete = new google.maps.places.Autocomplete(
    document.getElementById('autocomplete-input'), {types: ['geocode']});
    autocomplete.addListener('place_changed', getAddressDetails);
}
function getAddressDetails(){
    var place = autocomplete.getPlace();   
    window.lat = place.geometry.location.lat();
    window.long = place.geometry.location.lng();
}
function geolocate(){
  if (navigator.geolocation){
    navigator.geolocation.getCurrentPosition(function(position){
      var geolocation = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
        var circle = new google.maps.Circle(
        {center: geolocation, radius: position.coords.accuracy});
        autocomplete.setBounds(circle.getBounds());
    });
  }
}
</script>

This will be your input

<div id="autocomplete-container">
                            <input id="autocomplete-input" type="text" 
                            class="autocomplete" autocomplete="off" spellcheck="false" dir="auto"
                            placeholder="Location" onFocus="geolocate()">
                        </div>
newbdeveloper
  • 394
  • 3
  • 11
0

This code works fine for my projects

var autocomplete = new google.maps.places.Autocomplete(input, options);

    google.maps.event.addListener(autocomplete, 'place_changed', function() {
      var place = autocomplete.getPlace();
      var lat = place.geometry.location.lat();
      var lng = place.geometry.location.lng();
      var placeId = place.place_id;
      // to set city name, using the locality param
      var componentForm = {
        locality: 'short_name',
      };
      for (var i = 0; i < place.address_components.length; i++) {
        var addressType = place.address_components[i].types[0];
        if (componentForm[addressType]) {
          var val = place.address_components[i][componentForm[addressType]];
          document.getElementById("city").value = val;
        }
      }
      document.getElementById("latitude").value = lat;
      document.getElementById("longitude").value = lng;
      document.getElementById("location_id").value = placeId;
    });