Подтвердить что ты не робот

Как добавить окно поиска автозаполнения Google Карт?

Я пытаюсь добавить окно поиска автозаполнения Google на веб-сайт, чтобы пользователи могли как можно проще искать адрес.

Моя проблема заключается в том, что я рассмотрел многочисленные вопросы здесь, а также API Javascript Google Maps v3 в отношении этого и некоторых обучающих программ, но все они объединяют функции автозаполнения с отображением его на встроенной карте Google.

Мне не нужно отображать местоположение визуально, мне просто нужно окно автозаполнения, к сожалению, я не могу понять, какие части API имеют отношение к этому, и каждый пример, который я рассмотрел, включает в себя множество JS для сопоставления,

Кто-нибудь знает ресурс, который работает ТОЛЬКО с добавлением функций ввода автозаполнения.

Веб-сайт здесь.

Если вы нажмете "Калькулятор котировок" → > "Транспорт" → > "Собрать", вы увидите окно ввода, где я хотел бы добавить эту функциональность.

Я не прошу кого-нибудь сделать свою работу для меня, просто чтобы помочь мне найти то, что мне нужно.

Спасибо заранее.

4b9b3361

Ответ 1

Значительная часть этого кода может быть устранена.

Отрывок из HTML:

<head>
...
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
...
</head>
<body>
...
<input id="searchTextField" type="text" size="50">
...
</body>

JavaScript:

function initialize() {

var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
}

google.maps.event.addDomListener(window, 'load', initialize);

Вы можете увидеть пример http://www.redwoodtransit.org.

Ответ 2

Просто скопируйте и вставьте тот же самый код ниже.

<!DOCTYPE html>
<html>
    <head>
        <script src="https://maps.googleapis.com/maps/api/jsvv=3.exp&sensor=false&libraries=places"></script>
    </head>
    <body>
        <label for="locationTextField">Location</label>
        <input id="locationTextField" type="text" size="50">

        <script>
            function init() {
                var input = document.getElementById('locationTextField');
                var autocomplete = new google.maps.places.Autocomplete(input);
            }

            google.maps.event.addDomListener(window, 'load', init);
        </script>
    </body>
</html>

Хорошо отформатированный код можно найти по этой ссылке. http://jon.kim/how-to-add-google-maps-autocomplete-search-box/

Ответ 3

Используйте API Google Maps JavaScript с библиотекой мест, чтобы внедрить окно поиска автозаполнения карт Google на веб-странице.

HTML

<input id="searchInput" class="controls" type="text" placeholder="Enter a location">

JavaScript

<script>
function initMap() {
    var input = document.getElementById('searchInput');
    var autocomplete = new google.maps.places.Autocomplete(input);
}
</script>

Полное руководство, исходный код и живая демонстрация можно найти здесь - Окно поиска автозаполнения карт Google с окном Карты и Инфо

Ответ 4

// Bias the autocomplete object to the user geographical location,
// as supplied by the browser 'navigator.geolocation' object.
function geolocate() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(poenter code heresition) {
      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());
    });
  }
}

Ответ 5

Чтобы использовать API Google Maps/Places, вам необходимо использовать ключ API. Таким образом, URL-адрес API изменится с

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>

к

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>

Ответ 6

<!DOCTYPE html>
<html>
  <head>
    <title>Place Autocomplete Address Form</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      html, body, #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
    </style>
    <link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
    <script>
// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.

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 initialize() {
  // Create the autocomplete object, restricting the search
  // to geographical location types.
  autocomplete = new google.maps.places.Autocomplete(
      /** @type {HTMLInputElement} */(document.getElementById('autocomplete')),
      { types: ['geocode'] });
  // When the user selects an address from the dropdown,
  // populate the address fields in the form.
  google.maps.event.addListener(autocomplete, 'place_changed', function() {
    fillInAddress();
  });
}

// [START region_fillform]
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 fill 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;
    }
  }
}
// [END region_fillform]

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

    </script>

    <style>
      #locationField, #controls {
        position: relative;
        width: 480px;
      }
      #autocomplete {
        position: absolute;
        top: 0px;
        left: 0px;
        width: 99%;
      }
      .label {
        text-align: right;
        font-weight: bold;
        width: 100px;
        color: #303030;
      }
      #address {
        border: 1px solid #000090;
        background-color: #f0f0ff;
        width: 480px;
        padding-right: 2px;
      }
      #address td {
        font-size: 10pt;
      }
      .field {
        width: 99%;
      }
      .slimField {
        width: 80px;
      }
      .wideField {
        width: 200px;
      }
      #locationField {
        height: 20px;
        margin-bottom: 2px;
      }
    </style>
  </head>

  <body onload="initialize()">
    <div id="locationField">
      <input id="autocomplete" placeholder="Enter your address"
             onFocus="geolocate()" type="text"></input>
    </div>


  </body>
</html>

Ответ 7

Я использую jQuery здесь, чтобы получить введенный текст и обернуть весь код в $(document).ready(). Убедитесь, что у вас есть ключ API для веб-сервиса Google Адресов. Замените его в нижнем script файле.

<input type="text" id="location">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=[YOUR_KEY_HERE]&libraries=places"></script>
<script src="javascripts/scripts.js"></scripts>

Используйте файл script для загрузки класса автозаполнения. Ваш файл scripts.js будет выглядеть примерно так.

    // scripts.js custom js file
$(document).ready(function () {
   google.maps.event.addDomListener(window, 'load', initialize);
});

function initialize() {
    var input = document.getElementById('location');
    var autocomplete = new google.maps.places.Autocomplete(input);
}

Ответ 8

<input id="autocomplete" placeholder="Enter your address" type="text"/>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="https://mapenter code heres.googleapis.com/maps/api/js?key=AIzaSyC7vPqKI7qjaHCE1SPg6i_d1HWFv1BtODo&libraries=places"></script>
<script type="text/javascript">
    function initialize() {

        new google.maps.places.Autocomplete(
        (document.getElementById('autocomplete')), {
            types: ['geocode']
        });
    }

    initialize();

</script>