Python или IronPython

Вам нужно передать два входа автозаполнения. Вот обобщенная версия fillInAddress, которая будет обрабатывать несколько объектов автозаполнения с полями с уникальным расширением («2» в вашей второй версии формы):

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

    for (var component in componentForm) {
        if(!!document.getElementById(component + unique)){
            document.getElementById(component + unique).value = '';
            document.getElementById(component + unique).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] && document.getElementById(addressType + unique)) {
            var val = place.address_components[i][componentForm[addressType]];
            document.getElementById(addressType + unique).value = val;
        }
    }
}

Вызвать это следующим образом:

// 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.
autocomplete.addListener('place_changed', function () {
    fillInAddress(autocomplete, "");
});

// Create the second autocomplete object, restricting the search to geographical
// location types.
autocomplete2 = new google.maps.places.Autocomplete(
/** @type {!HTMLInputElement} */
(document.getElementById('autocomplete2')), {
    types: ['geocode']
});
autocomplete2.addListener('place_changed', function () {
    fillInAddress(autocomplete2, "2");
});

фрагмент рабочего кода:

// 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, autocomplete2;
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(
    /** @type {!HTMLInputElement} */
    (document.getElementById('autocomplete')), {
      types: ['geocode']
    });

  // When the user selects an address from the dropdown, populate the address
  // fields in the form.
  autocomplete.addListener('place_changed', function() {
    fillInAddress(autocomplete, "");
  });

  autocomplete2 = new google.maps.places.Autocomplete(
    /** @type {!HTMLInputElement} */
    (document.getElementById('autocomplete2')), {
      types: ['geocode']
    });
  autocomplete2.addListener('place_changed', function() {
    fillInAddress(autocomplete2, "2");
  });

}

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

  for (var component in componentForm) {
    if (!!document.getElementById(component + unique)) {
      document.getElementById(component + unique).value = '';
      document.getElementById(component + unique).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] && document.getElementById(addressType + unique)) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType + unique).value = val;
    }
  }
}
google.maps.event.addDomListener(window, "load", initAutocomplete);

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 src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="locationField">
  <input id="autocomplete" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
</div>
<div id="addressone">
  <input type="text" id="street_number" name="street_number" />
  <input type="text" id="route" name="street_name" />
  <input type="text" id="locality" name="town_city" />
  <input type="text" id="administrative_area_level_1" name="administrative_area_level_1" />
  <input type="text" id="postal_code" name="postcode" />
  <input type="text" id="country" name="country" />
</div>
<div id="locationField2">
  <input id="autocomplete2" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
</div>
<div id="addresstwo">
  <input type="text" id="street_number2" name="street_number2" />
  <input type="text" id="route2" name="street_name2" />
  <input type="text" id="locality2" name="town_city2" />
  <input type="text" id="administrative_area_level_12" name="administrative_area_level_12" />
  <input type="text" id="postal_code2" name="postcode2" />
  <input type="text" id="country2" name="country2" />
</div>

31
задан johnc 28 February 2009 в 21:04
поделиться

8 ответов

Существует много важных различий:

  1. Совместимость с другими языками.NET. Можно пользоваться другими библиотеками.NET из приложения IronPython или использовать IronPython из приложения C#, например. Эта совместимость увеличивается с перемещением к большей поддержке динамических типов в.NET 4.0. Для большого количества детали об этом см. эти два представления в 2008 PDC.
  2. Лучший параллелизм / многоядерная поддержка, из-за отсутствия GIL. (Обратите внимание, что GIL не запрещает поточную обработку на одножильной машине---, это только ограничивает производительность на многоядерных машинах.)
  3. Ограниченные возможности использовать расширения Python C. Бронированный проект добивается значительных успехов к улучшению этого---, который они почти получили работа Numpy!
  4. Меньше межплатформенной поддержки; в основном у Вас есть CLR и Моно . Моно является впечатляющим, тем не менее, и работает на многих платформах---, и у них есть реализация Silverlight, названной Лунный свет .
  5. Сообщения об улучшенной производительности, хотя я не изучил это тщательно.
  6. задержка Функции: так как CPython является ссылочной реализацией Python, он имеет "последние и самые большие" функции Python, тогда как IronPython обязательно отстает. Многие люди не находят, что это проблема.
31
ответ дан 27 November 2019 в 20:36
поделиться

Существуют некоторые тонкие различия в том, как Вы пишете свой код, но самое большое различие находится в библиотеках, которые Вы имеете в наличии.

С IronPython, Вы имеете все библиотеки .NET в наличии, но за счет некоторых "нормальных" библиотек Python, которые не были портированы к.Net VM I, думают.

В основном, необходимо ожидать, что синтаксис и идиомы будут тем же, но сценарий, записанный для привычки IronPython, выполненной, при попытке дать его "обычному" интерпретатору Python. Наоборот, вероятно, более вероятно, но там также Вы найдете различия, я думаю.

13
ответ дан 27 November 2019 в 20:36
поделиться

Посмотрите сообщение в блоге , IronPython является односторонним логическим элементом . Это суммирует некоторые вещи, которые я узнал о IronPython от задавания вопросов на StackOverflow.

3
ответ дан 27 November 2019 в 20:36
поделиться

Ну, это обычно быстрее.

не Может использовать модули и только имеет подмножество библиотеки.

Вот список различий.

6
ответ дан 27 November 2019 в 20:36
поделиться

Python является Python, единственная разница - то, что IronPython был разработан для работы CLR (Платформа.NET), и как таковой, может взаимодействовать и использовать блоки.NET, записанные на других языках.NET. Таким образом, если Ваша платформа является Windows, и Вы также используете.NET, или Ваша компания делает тогда должен рассмотреть IronPython.

2
ответ дан 27 November 2019 в 20:36
поделиться

Один из профессионалов IronPython - то, что, в отличие от CPython, IronPython не использует Глобальную Блокировку Интерпретатора, таким образом делая поточную обработку более эффективного.

В стандартной реализации Python, потоки захватывают GIL на каждом доступе к объекту. Это ограничивает параллельное выполнение, которое имеет значение особенно, если Вы ожидаете полностью использовать несколько центральных процессоров.

2
ответ дан 27 November 2019 в 20:36
поделиться

Pro: можно работать IronPython в браузере , если Silverlight установлена.

2
ответ дан 27 November 2019 в 20:36
поделиться

Это также зависит от того, хотите ли Вы, чтобы Ваш код работал над Linux. Не знайте, будет ли IronPython работать над чем-нибудь около платформ окон.

0
ответ дан 27 November 2019 в 20:36
поделиться
Другие вопросы по тегам:

Похожие вопросы: