document.getElementById('suggest').addEventListener('change', function(e) {
let adress = e.target.value
geocode(adress)
console.log(val)
})
document.getElementById('suggest').addEventListener('change', function(e) {
let address = e.target.value.trim() // убирает пробелы в начале и конце
geocode(address)
console.log(value)
})
document.getElementById('suggest').addEventListener('change', function(e) {
let address = e.target.value.trim() // убирает пробелы в начале и конце
geocode(address)
console.log(address)
})
Может как то при клике на выпадающий список сначала записать в input а потом отдавать геокодеру?
ymaps.ready(init);
function init() {
var startPlacemark, endPlacemark, multiRoute
let coord_start = ['71.406975', '51.089227'];
var DELIVERY_TARIFF = 100,
MINIMUM_COST = 200,
myMap = new ymaps.Map('map', {
center: coord_start,
zoom: 9,
controls: []
}),
zoomControl = new ymaps.control.ZoomControl({
options: {
size: 'small',
float: 'none',
position: {
bottom: 145,
right: 10
}
}
});
var suggestView = new ymaps.SuggestView('suggest', {
provider: {
suggest: (function(request, options) {
return ymaps.suggest("Нур-Султан," + request);
})
}
});
var searchControl = new ymaps.control.SearchControl({
options: {
provider: 'yandex#map',
noPlacemark: true
}
});
myMap.controls.add(searchControl);
startPlacemark = new ymaps.Placemark(coord_start, {
balloonContent: 'Кабанбай Батыра, 62',
}, {
hideIconOnBalloonOpen: false
});
searchControl.events.add('resultselect', function(e) {
var results = searchControl.getResultsArray();
var selected = searchControl.getSelectedIndex();
coord_end = results[selected].geometry.getCoordinates();
addRoute(coord_start, coord_end)
})
function createPlacemark(coords) {
return new ymaps.Placemark(coords, {
iconCaption: 'поиск...'
}, {
preset: 'islands#violetDotIconWithCaption',
draggable: false
});
}
myMap.events.add('click', function(e) {
let coord_end = e.get('coords');
addRoute(coord_start, coord_end)
});
function addEndPlacemark(coord_end) {
if (endPlacemark) endPlacemark.geometry.setCoordinates(end_coords);
else {
endPlacemark = createPlacemark(end_coords);
myMap.geoObjects.add(endPlacemark);
}
coord_end = endPlacemark.geometry.getCoordinates()
getAddress(coord_end);
myMap.geoObjects.add(endPlacemark);
}
function getAddress(coords) {
endPlacemark.properties.set('iconCaption', 'поиск...');
ymaps.geocode(coords).then(function(res) {
var firstGeoObject = res.geoObjects.get(0);
endPlacemark.properties
.set({
iconCaption: [
firstGeoObject.getLocalities().length ? firstGeoObject.getLocalities() : firstGeoObject.getAdministrativeAreas(),
firstGeoObject.getThoroughfare() || firstGeoObject.getPremise()
].filter(Boolean).join(', '),
balloonContent: firstGeoObject.getAddressLine()
});
});
}
function addRoute(coord_start, coord_end) {
if (multiRoute) multiRoute.model.setReferencePoints([coord_start, coord_end]);
else {
multiRoute = new ymaps.multiRouter.MultiRoute(
{
referencePoints: [
coord_start,
coord_end
],
params: {
results: 1
}
},
{
boundsAutoApply: true
}
);
myMap.geoObjects.add(multiRoute);
}
multiRoute.model.events.add('requestsuccess', function() {
let distance = multiRoute.getActiveRoute().properties.get("distance")
let distance_km = Math.round(distance.value / 1000)
let price = calculate(distance_km)
});
}
myMap.controls.add(zoomControl);
myMap.controls.add(searchControl);
myMap.geoObjects.add(startPlacemark);
function calculate(routeLength) {
return Math.max(routeLength * DELIVERY_TARIFF, MINIMUM_COST);
}
let searchAddress = document.getElementById('suggest');
searchAddress.onchange = (e) => {
e.preventDefault();
let address = e.target.value.trim();
document.getElementById('suggest').value = address;
geocode(address);
console.log(address);
}
function geocode(address) {
var request = address
ymaps.geocode(request).then(
function(res) {
var obj = res.geoObjects.get(0), error, hint;
if (obj) {
switch (obj.properties.get('metaDataProperty.GeocoderMetaData.precision')) {
case 'exact':
break;
case 'number':
case 'near':
case 'range':
error = 'Неточный адрес, требуется уточнение';
hint = 'Уточните номер дома';
break;
case 'street':
error = 'Неполный адрес, требуется уточнение';
hint = 'Уточните номер дома';
break;
case 'other':
default:
error = 'Неточный адрес, требуется уточнение';
hint = 'Уточните адрес';
}
} else {
error = 'Адрес не найден';
hint = 'Уточните адрес';
}
if (error === 'Адрес не найден') showError(error)
else if (error === 'Неполный адрес') searchAddress.focus()
else {
coord_end = obj.geometry.getCoordinates()
addRoute(coord_start, coord_end)
}
},
function(e) {
console.log(e)
}
)
}
function showError(message) {
searchAddress.focus();
console.log(message);
}
}
function init() {
....
// добавляем в любом удобном месте внутри
suggestView.state.events.add('change', function () {
var activeIndex = suggestView.state.get('activeIndex');
if (typeof activeIndex == 'number') {
activeItem = suggestView.state.get('items')[activeIndex];
}
if (activeItem && activeItem.value != searchAddress.value) {
searchAddress.value = activeItem.value;
}
});
...
});