Jos*_*hba 8 javascript jquery google-maps autocomplete google-maps-api-3
我正在开发一个足够接近谷歌样本https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform的网页,它运行正常.
但是我还需要添加一个功能,即默认将自动完成的值设置为当前用户城市.
我正在使用以下代码来使用HTML5中的地理位置API来获取登录用户的城市和国家/地区.然而,挑战在于使自动完成接受此值作为其默认值.当我尝试将值直接放在文本框中时,自动完成会将其视为错误值.
navigator.geolocation.getCurrentPosition(function(pos) {
var currentLocation = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
var geocoder = new google.maps.Geocoder();
var city = "";
var country = "";
geocoder.geocode({'latLng': currentLocation}, function(results, status, from) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
for (var i = 0; i < results[0].address_components.length; i++) {
for (var b = 0; b < results[0].address_components[i].types.length; b++) {
if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
city = results[0].address_components[i];
break;
}
if (results[0].address_components[i].types[b] == "country") {
country = results[0].address_components[i];
break;
}
}
}
var fromDefault = city.long_name + " - " + country.long_name;
$('#address-from').val(fromDefault);
}
}
});
},
function(error) {
alert('Unable to get location: ' + error.message);
}, options);
Run Code Online (Sandbox Code Playgroud)
知道如何手动填写自动填充文本框的默认值吗?
我在尝试解决类似的用例时填写了这篇文章(用自己搜索的最后一个位置填充自动填充).
据我所知,无法为自动填充设置默认值,因为它被识别为一个地方.但是,我认为您可以使用自动填充服务模拟此效果(示例 - 另请参阅#AutocompletePrediction和#PlacesService上的参考部分):
这会让您的用户感觉自动填充功能正在使用中.如果结果是他们需要的,那太好了!如果他们想要搜索其他地方,请设置自动完成功能以侦听place_changed并运行autocomplete.getPlace(),然后执行相同的回调.
小智 5
当Map初始加载时,我有同样的要求设置初始位置.
我就这样做了:
正如Jon Hannah所提到的,我使用自动完成服务来获得预测,然后使用第一个预测来获取Place(使用place_id).使用我的默认位置字符串填充Autocompelete输入.最后触发了place_change事件.
this.input.nativeElement.value = this.testLocationStr;
let autocompleteService = new google.maps.places.AutocompleteService();
let request = {input: this.testLocationStr};
autocompleteService.getPlacePredictions(request, (predictionsArr, placesServiceStatus) => {
console.log('getting place predictions :: predictionsArr = ', predictionsArr, '\n',
'placesServiceStatus = ', placesServiceStatus);
let placeRequest = {placeId: predictionsArr[0].place_id};
let placeService = new google.maps.places.PlacesService(this.mapObj);
placeService.getDetails(placeRequest, (placeResult, placeServiceStatus) => {
console.log('placeService :: placeResult = ', placeResult, '\n',
'placeServiceStatus = ', placeServiceStatus);
this._handlePlaceChange(placeResult);
});
});
Run Code Online (Sandbox Code Playgroud)
Plunker:https://plnkr.co/edit/9oN6Kg ? p = preview
| 归档时间: |
|
| 查看次数: |
6300 次 |
| 最近记录: |