Calling a JS command in two places on a page.

Posted 7 months ago by chrisgrim

Hi, I am using the google places api to autocomplete the search on my site. My issue is on the create event page. I am trying to call the autocomplete for the search on the nav bar and in the create form further down the page. I can only seem to ever get one of them working at the same time. I have this in my HTML for the navbar

<input class="form-control" id="navsearch" type="text" placeholder="Search..." name="term">

and this in the html for the create event

<input id="navsearch" placeholder="Enter address to store" type="text"></input>

The JS I am calling is here

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 to geographical
  // location types.
  autocomplete = new google.maps.places.Autocomplete(
    (document.getElementById('navsearch')), {
      types: ['geocode']
    });
  autocomplete.addListener('place_changed', addlatlong);
}

function addlatlong() {

  //this is what adds lat and long to search in nav

var place = autocomplete.getPlace();

var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();

document.getElementById("latitude").value = latitude;
document.getElementById("longitude").value = longitude;

//this is where it adds all info to fields in create

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

  console.log(`${latitude}`)
  console.log(`${longitude}`)

  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;
    }
  }

}

This works right now for the nav search bar, but gives me nothing in the create part further down the page.

Thanks for any help!!

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.