#javascript #ajax
Вопрос:
У меня есть скрипт, который создает простую боковую панель, и я загружаю константу под названием «Магазины», чтобы заполнить боковую панель.
Вот моя проблема: когда я загружаю эту постоянную переменную (даже с помощью простых фиктивных данных), она отлично работает при загрузке страницы и заполняет боковую панель. Однако, когда я нажимаю на строку поиска, вызывается функция getApi, она не заполняет боковую панель асинхронно (даже если я просто использую фиктивные данные в функции успеха моего вызова ajax.
Я думаю, что проблема может быть в моей функции под названием buildLocationList. Возможно ли, что эта функция вызывается только при загрузке страницы, поскольку она вызывается при загрузке карты?
Если да, то как бы я сделал это так, чтобы загрузка карты происходила при успешном выполнении моего вызова ajax?
<head>
<link href="https://api.mapbox.com/mapbox-gl-js/v2.4.1/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v2.4.1/mapbox-gl.js"></script>
</head>
<div class="box">
<input id="zipSearch" type="text" name="search" class="round" onclick="getLocation()" placeholder="Enter Zip Code" />
</div>
<div>
<div class="sidebar">
<div class="heading">
<h1>Our locations</h1>
</div>
<div id="listings" class="listings"></div>
</div>
</div>
<script type="text/javascript">
var result = document.getElementById("zipSearch");
const Http = new XMLHttpRequest();
function getLocation() {
console.log("getLocation Called");
var bdcApi = "https://api.bigdatacloud.net/data/reverse-geocode-client"
navigator.geolocation.getCurrentPosition(
(position) => {
bdcApi = bdcApi
"?latitude=" position.coords.latitude
"amp;longitude=" position.coords.longitude
"amp;localityLanguage=en";
getApi(bdcApi);
},
(err) => { getApi(bdcApi); },
{
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
});
}
function getApi(bdcApi) {
Http.open("GET", bdcApi);
Http.send();
Http.onreadystatechange = function () {
if (this.readyState == 4 amp;amp; this.status == 200) {
//result.innerHTML = this.responseText;
var data = JSON.parse(this.responseText);
var zip = data.postcode;
result.value = zip
console.log(zip);
jQuery.ajax({
type: 'GET',
url: "<?php echo JURI::base() . "index.php?option=com_ajaxamp;module=hunter_maps_devamp;method=getStoresByZipamp;zip="?>" zip "amp;format=json",
datatype : "application/json",
success:function(data){
console.log('success');
//mock data
//const stores = {
// 'type': 'FeatureCollection',
// 'features': [
// {
// 'type': 'Feature',
// 'geometry': {
// 'type': 'Point',
// 'coordinates': [-77.034084142948, 38.909671288923]
// },
// 'properties': {
// 'storeImage' : 'https://via.placeholder.com/150',
// 'storeName' : 'Test Store',
// 'phoneFormatted': '(202) 234-7777',
// 'phone': '2022347336',
// 'address': '1471 P St NW',
// 'city': 'Washington DC',
// 'country': 'United States',
// 'crossStreet': 'at 15th St NW',
// 'postalCode': '20005',
// 'state': 'D.C.'
// }
// },
// ]
// };
const stores = data;
console.log(stores);
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
}
};
}
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v10',
center: [-77.034084142948, 38.909671288923],
zoom: 13,
scrollZoom: false
});
//mock data
//const stores = {
// 'type': 'FeatureCollection',
// 'features': [
// {
// 'type': 'Feature',
// 'geometry': {
// 'type': 'Point',
// 'coordinates': [-77.034084142948, 38.909671288923]
// },
// 'properties': {
// 'storeImage' : 'https://via.placeholder.com/150',
// 'storeName' : 'Test Store',
// 'phoneFormatted': '(202) 234-7777',
// 'phone': '2022347336',
// 'address': '1471 P St NW',
// 'city': 'Washington DC',
// 'country': 'United States',
// 'crossStreet': 'at 15th St NW',
// 'postalCode': '20005',
// 'state': 'D.C.'
// }
// },
// ]
// };
/**
* Assign a unique id to each store. You'll use this `id`
* later to associate each point on the map with a listing
* in the sidebar.
*/
stores.features.forEach((store, i) => {
store.properties.id = i;
});
/**
* Wait until the map loads to make changes to the map.
*/
map.on('load', () => {
/**
* This is where your '.addLayer()' used to be, instead
* add only the source without styling a layer
*/
map.addSource('places', {
'type': 'geojson',
'data': stores
});
/**
* Add all the things to the page:
* - The location listings on the side of the page
* - The markers onto the map
*/
buildLocationList(stores);
});
/**
* Add a listing for each store to the sidebar.
**/
function buildLocationList({ features }) {
for (const { properties } of features) {
/* Add a new listing section to the sidebar. */
const listings = document.getElementById('listings');
const listing = listings.appendChild(document.createElement('div'));
/* Assign a unique `id` to the listing. */
listing.id = `listing-${properties.id}`;
/* Assign the `item` class to each listing for styling. */
listing.className = 'item';
const image = listing.appendChild(document.createElement('a'));
if (properties.storeImage){
image.innerHTML = `<img src=/images/coupons/thumbs/${properties.storeImage} style="margin-right:10px; margin-bottom:8px;"/>`;
}
/* Add the link to the individual listing created above. */
const link = listing.appendChild(document.createElement('a'));
link.href = '#';
link.className = 'title';
link.id = `link-${properties.id}`;
link.innerHTML = `${properties.storeName}`;
/* Add details to the individual listing. */
const details = listing.appendChild(document.createElement('div'));
details.innerHTML = `${properties.address}</br>`;
details.innerHTML = `${properties.city}, `;
details.innerHTML = `${properties.state}` ;
details.innerHTML = ` ${properties.postalCode}`;
if (properties.phone) {
details.innerHTML = ` amp;middot; ${properties.phoneFormatted}`;
}
}
}
</script>