首页 > 解决方案 > 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需要全局定义的函数或初始化程序。但是,在我的代码中,这种设置对我不起作用,因为在单击位置图标之前没有可用的地址,因此无法将地址填充到地图中。

我不知道我是否能够很好地解释,但我希望我的问题不会令人困惑。

请问,我该如何处理或解决这个问题。任何帮助表示赞赏。提前致谢。

标签: javascriptgoogle-maps

解决方案


我能够通过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));
};

推荐阅读