javascript - JavaScript:使用动态数据显示交互式地图
问题描述
我正在尝试使用 Google Maps API 显示带有动态数据的交互式地图。但是,我无法弄清楚如何在我的代码中进行设置。
在我的网站中,我有卡片列表,我想制作它,以便当单击每张卡片中的特定元素时,将根据附加到卡片的位置数据显示交互式地图。
我的代码如下所示:
卡片列表
HTML
<div class="list-group ${type}-item" id="${result.rows[x].id}" onclick="propertyClicked(window.event, ${result.rows[x].id});">
<a class="list-group-item list-group-item-action flex-column align-items-start">
<div class="d-flex w-100 justify-content-between">
<h5 class="mb-1">${result.rows[x].reporterName}</h5>
<small>${moment(new Date(parseInt(result.rows[x].datetime)).toDatetimeLocal('unformatted').toString(), 'YYYYMMDDhhmmss').fromNow()}</small>
</div>
<p class="mb-1">Bedrooms: ${result.rows[x].bedrooms}</p>
<p class="mb-1">Furniture Types: ${result.rows[x].furnitureTypes === '' ? 'None' : result.rows[x].furnitureTypes}</p>
<p class="mb-1">Location: ${result.rows[x].propertyLocation === '' ? 'No Location' : result.rows[x].propertyLocation}</p>
<div class="d-flex w-100 justify-content-between">
<p class="mb-1">Monthly Rent Price: $${parseFloat(result.rows[x].monthlyRentPrice)}</p>
<div>
<ion-icon name="pin" class="mr-4 purple note-icon" id="note-location" onclick="onLocationClicked('${result.rows[x].propertyLocation}');"></ion-icon>
<ion-icon name="create" class="mr-4 purple note-icon" id="edit-note" onclick="onEditClicked(${result.rows[x].id});"></ion-icon>
<ion-icon name="trash" class="note-icon purple" id="delete-note" onclick="onDeleteClicked(${result.rows[x].id}, '${type}');"></ion-icon>
</div>
</div>
</a>
</div>
在上面的 HTML 中,我在位置图标上有一个 onclick 侦听器,这是函数:
JS
onLocationClicked = address => {
let lat, lng;
axios.post(`https://maps.googleapis.com/maps/api/geocode/json?address=${address}&key=${API_KEY}`).then(response => {
lat = response.data.results[0].geometry.location.lat;
lng = response.data.results[0].geometry.location.lng;
document.getElementsByClassName('modal-title')[0].textContent = 'Location';
document.getElementsByClassName('modal-body')[0].innerHTML = '';
document.getElementsByClassName('modal-body')[0].insertAdjacentHTML(
'beforeend',
`<div id='map' style='height:100%'></div>`
);
toggleElDisplay('delete-note-btn', 'id');
map = new google.maps.Map(document.getElementById('map'), {
center: {lat, lng},
zoom: 8
});
document.getElementById('modal-close').textContent = 'Close';
toggleElDisplay('modal-close', 'id', null, true);
$('#myModal').modal('show');
document.getElementById('modal-close').addEventListener('click', () => {
document.getElementsByClassName('modal-body')[0].innerHTML = '';
});
}).catch(error => console.error(error));
};
我的问题是,由于 Google Maps API 的工作方式,它需要一个initMap
需要全局定义的函数或初始化程序。但是,在我的代码中,这种设置对我不起作用,因为在单击位置图标之前没有可用的地址,因此无法将地址填充到地图中。
我不知道我是否能够很好地解释,但我希望我的问题不会令人困惑。
请问,我该如何处理或解决这个问题。任何帮助表示赞赏。提前致谢。
解决方案
我能够通过initMap
全局创建函数并使用虚拟位置数据设置地图来解决此问题。
然后,当单击位置图标时,我将地图的位置数据更改为适当的位置数据,然后显示地图。
所以我的 JS 现在看起来像这样:
initMap = () => {
let myLatlng = new google.maps.LatLng(-25.363882, 131.044922);
let mapOptions = { zoom: 10, center: myLatlng };
map = new google.maps.Map(document.getElementById('rough-map'), mapOptions);
let marker = new google.maps.Marker({
position: myLatlng,
title: "Random Location"
});
marker.setMap(map);
toggleElDisplay('rough-map', 'id');
};
onLocationClicked = address => {
let lat, lng;
axios.post(`https://maps.googleapis.com/maps/api/geocode/json?address=${address}&key=${API_KEY}`).then(response => {
lat = response.data.results[0].geometry.location.lat;
lng = response.data.results[0].geometry.location.lng;
document.getElementsByClassName('modal-title')[0].textContent = 'Location';
document.getElementsByClassName('modal-body')[0].innerHTML = '';
document.getElementsByClassName('modal-body')[0].insertAdjacentHTML(
'beforeend',
`<div id='map' style='min-height: 300px; max-height: 600px;'></div>`
);
toggleElDisplay('delete-note-btn', 'id');
let myLatlng = new google.maps.LatLng(lat, lng);
let mapOptions = { zoom: 15, center: myLatlng };
map = new google.maps.Map(document.getElementById('map'), mapOptions);
let marker = new google.maps.Marker({ position: myLatlng, title: address });
marker.setMap(map);
document.getElementById('modal-close').textContent = 'Close';
toggleElDisplay('modal-close', 'id', null, true);
$('#myModal').modal('show');
document.getElementById('modal-close').addEventListener('click', () => {
document.getElementsByClassName('modal-body')[0].innerHTML = '';
});
}).catch(error => console.error(error));
};
推荐阅读
- django-rest-framework - 在 Django Rest Framework 问题 401 中使用身份验证测试 POST
- ava - 我可以以某种方式声明测试预计会有未处理的拒绝吗?
- image-processing - 无法从 USGS 获取 TIFF 文件以打开
- javascript - Laravel 分页链接问题与设计
- error-handling - 宏匹配臂模式“没有规则需要令牌`if`”
- c# - 无法创建 HttpGet 控制器以使用身份查找用户详细信息
- python - 通过字符串索引选择 Pandas DataFrame 的行
- ruby-on-rails - “堆栈级别太深” Rails 5 在“define_generate_prefix”
- javascript - 如何像使用普通 ES6 文件一样从使用 babel 和 webpack 生成的文件中导入类?
- git - 命令提示符中的奇怪错误,尝试使用 PIP 安装包