Google Api not working on appended input

依然范特西╮ 提交于 2020-01-07 03:53:12

问题


Background:

I am trying to add the google address search to an online storefront. I do not have access to the actual html of the site but I am allowed to input code into the header, footer, and include any css or js page I would like. I had everything working in the beginning. I had the input in the header and was able to search for an address.

Which created:

So after I got my code working it was time to move the input down below with the other address inputs. I wanted to use javascript to append this input in a div based on he parent ID. So I did this with this code:

window.onload = function () {
    var input = document.createElement('div');
    input.setAttribute("id", "locationField");
    input.innerHTML = '<input id="autocomplete" placeholder="Enter your address" onfocus="geolocate()" type="text" autocomplete="off">';

    var form = document.getElementById('NameAdd');
    form.insertBefore(input, form.firstChild);
};

Which produced this:

Now that I am including the input this way it is not showing google results. When inspecting the elements of the page everything looks fine. What am I doing wrong?


回答1:


The google.maps.places.Autocomplete constructor takes a <input> element, not a <div>.

This works for me:

window.onload = function() {
  var inputDiv = document.createElement('div');
  inputDiv.setAttribute("id", "locationField");

  // create input element dynamically so don't need to wait for it to render
  var input = document.createElement('input');
  input.setAttribute("id", "autocomplete");
  input.setAttribute("placeholder", "Enter your address");
  input.setAttribute("type", "text");
  input.setAttribute("autocomplete", "off");
  inputDiv.appendChild(input);

  var form = document.getElementById('NameAdd');
  form.insertBefore(input, form.firstChild);
  var autocomplete = new google.maps.places.Autocomplete(input);
};
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<form id="NameAdd">
  <br />
  <input id="Name" value="name" />
  <input id="Address" value="address" />
</form>


来源:https://stackoverflow.com/questions/33899125/google-api-not-working-on-appended-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!