jQuery如何基于AJAX获取的城市数据实现点击展示城市地图功能
实现方案
你需要对现有代码做三处核心修改即可完成需求:
- 给
city map按钮添加唯一ID,绑定点击事件,初始设为禁用状态避免用户未选城市时误触 - 在城市列表加载完成的回调中存储全量城市数据,同时启用按钮
- 点击按钮时读取当前选中的城市信息,打开新窗口渲染地图
完整修改后代码
<html> <head> <style> body { background-color: #E8EAF6; } main { margin: 1em; width: 60%; padding: 1em; } select { padding: 0.5em; } #results { margin-top: 0.5em; margin-bottom: 1em; } button { padding: 0.5em 1em; cursor: pointer; } button:disabled { cursor: not-allowed; opacity: 0.6; } </style> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script> $(function() { // 全局存储当前国家对应的城市列表数据 let cityList = []; $("#country").change(function() { // 切换国家时先禁用按钮,清空旧的城市数据 $('#cityMapBtn').prop('disabled', true); cityList = []; var param = "iso=" + $('#country').val(); $.get("http://www.randyconnolly.com/funwebdev/services/travel/cities.php", param) .done(function (data) { // 存储城市全量数据,包含ID、名称、经纬度等字段 cityList = data; var select = $("<select id='cities'></select>"); $.each(data, function(index,city) { select.append('<option value="' + city.id + '">' + city.name + "</option>"); }); $("#results").empty().append(select); // 城市加载完成后启用地图按钮 $('#cityMapBtn').prop('disabled', false); }) .fail(function (jqXHR) { alert("Error: " + jqXHR.status); }) .always(function () { console.log("service cities request finished"); }); }); // 绑定地图按钮点击事件 $('#cityMapBtn').on('click', function() { const selectedCityId = $('#cities').val(); // 匹配当前选中城市的全量信息 const selectedCity = cityList.find(item => item.id == selectedCityId); if (!selectedCity) { alert('请先选择国家和城市'); return; } // 打开新窗口渲染地图 const mapWin = window.open('', '_blank'); const offset = 0.05; // 地图显示范围偏移量,可调整 mapWin.document.write(` <!DOCTYPE html> <html> <head> <title>${selectedCity.name}地图</title> <style> * {margin:0;padding:0;border:none;} iframe {width:100%;height:100vh;} </style> </head> <body> <iframe src="https://www.openstreetmap.org/export/embed.html?bbox=${selectedCity.lon-offset}%2C${selectedCity.lat-offset}%2C${selectedCity.lon+offset}%2C${selectedCity.lat+offset}&layer=mapnik&marker=${selectedCity.lat}%2C${selectedCity.lon}"></iframe> </body> </html> `); mapWin.document.close(); }) }); </script> </head> <body> <main> <select id="country"> <option value=0>Select a country</option> <option value='CA'>Canada</option> <option value='FR'>France</option> <option value='DE'>Germany</option> <option value='IT'>Italy</option> <option value='US'>United States</option> </select> <div id="results"></div> <button id="cityMapBtn" disabled> city map </button> </main> </body> </html>
说明
- 你提到的接口返回的城市数组中每个城市对象默认包含
lat(纬度)、lon(经度)字段,上述代码直接使用该字段渲染地图,如果接口返回的字段名不同,替换为对应字段即可 - 每次点击按钮都会实时读取城市下拉框的当前选中值,切换城市后点击按钮会自动加载新选中城市的地图,满足需求
- 如果不需要使用第三方地图嵌入,可替换iframe部分为自定义地图渲染逻辑即可
内容的提问来源于stack exchange,提问作者Adam Gong
相关产品推荐
相关产品推荐

