【问题标题】:If there is no lat/lng valu, then don't plot it on the map [closed]如果没有纬度/经度值,则不要在地图上绘制它[关闭]
【发布时间】:2020-12-28 15:21:35
【问题描述】:

在调用我自己的 API(这是 MongoDB Atlas 上的餐厅数据库)后,我有一个工作页面成功地在地图上绘制标记。例如。如果我搜索“Fleetwood”,它将在地图上标出 Fleetwood 的所有餐厅。

但是,如果我搜索缺少 lat/lng 数值的位置,它会中断。我的餐厅数据库有 50 万多个地点,而且很多地方没有纬度/经度。

编辑: 我试图调整我的代码,以免在标记没有 lat/lng 值的情况下将它们推送到我的数组中(但我的尝试失败了)。 这是我的尝试之一。我尝试使用 IF 语句来表示,如果 data[i].Geocode_Latitude 不为空,则将其分配给变量。但错误是get是: ReferenceError: pot 没有定义 在 getTown (index_try7_test.html:99)

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Javascript Calling APIs</title>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <script src="https://maps.googleapis.com/maps/api/js?key=INSERT_GOOGLE_KEY_HERE&callback=initMap&libraries=&v=weekly" async defer></script>

  <style type="text/css">
    /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
    #map {
      margin: auto;
      height: 750px;
      width: 75%;
    }

    /* Optional: Makes the sample page fill the window. */
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
  </style>
</head>

<body>
  <h1>Test</h1>
  <div id="map"></div>
  <p id="demo"></p>

  <input type="text" placeholder="Type something..." id="myInput">
  <button type="button" onclick="getInputValue(); deleteOverlays()">Get Value</button>


  <button type="button" onclick="reset();">Reset</button>


  <script>
    function deleteOverlays() {
      if (markersArray) {
        for (i in markersArray) {
          markersArray[i].setMap(null);
        }
        markersArray.length = 0;
      }
    }

    function reset() {
      map.setZoom(6);
      deleteOverlays();
    };

    var markersArray = [];
    console.log(markersArray);

    function getInputValue() {
      var myHeaders = new Headers();
      myHeaders.append("x-rapidapi-key", "169034d4a5msha6f68db3ab64e43p12abf2jsnabff656340a7");

      var requestOptions = {
        method: 'GET',
        headers: myHeaders,
        redirect: 'follow'
      };

      var myHeaders = new Headers();
      myHeaders.append("x-rapidapi-key", "169034d4a5msha6f68db3ab64e43p12abf2jsnabff656340a7");
      const api_url = 'https://wyre-data.p.rapidapi.com/restaurants/town'
      var town = document.getElementById("myInput").value;
      var requestOptions = {
        method: 'GET',
        headers: myHeaders,
        redirect: 'follow'
      };

      async function getTown() {

        const response = await fetch(api_url + '/' + town, requestOptions);
        const data = await response.json();
        //console.log(data);

        var bounds = new google.maps.LatLngBounds();
        for (i = 0; i < data.length; i++) {
          let la = data[i].Geocode_Latitude;
          let lo = data[i].Geocode_Longitude;

if (data[i].Geocode_Latitude !== null) {
  let pot = {
    lat: la,
    lng: lo
  };
}

          let marker = new google.maps.Marker({
            position: pot,
            map: map,
            icon: 'pin.png'
          });

// if (marker.position.lat !== null) { markersArray.push(marker) };

          markersArray.push(marker);
          //console.log(pot);
          //console.log([i]);
          console.log(markersArray);

          bounds.extend(marker.position);
          google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
              infowindow.setContent(data[i][0]);
              infowindow.open(map, marker);
            }
          })(marker, i));
        };


        /* Zoom to all markers found, centre on them and fit to map boundary */
        map.fitBounds(bounds);

      }

      getTown();

    }

    let map;

    function initMap() {
      map = new google.maps.Map(document.getElementById("map"), {
        center: {
          lat: 54.9421859,
          lng: -2.7433701
        },
        zoom: 6,
      });
    }
  </script>

  <h2>The End...</h2>
</body>

</html>

【问题讨论】:

  • “我认为展示我的工作代码更有用” - 这根本没有帮助,也不是 SO 的范围。请添加您的尝试、由此产生的任何错误消息以及您尝试解决的问题 -> minimal reproducible example
  • 但这不应该只是一个简单的if (...) { markersArray.push(...) }
  • @Andreas 我编辑了我的帖子,向您展示我尝试过的一些事情以及错误。我是初学者,所以这很可能是一个非常基本的问题。谢谢
  • 为什么你认为“未定义”的值会是null? -> console.log(data[i].Geocode_Latitude)
  • 谢谢 Andreas,我认为 null 与 undefined 相同——现在我知道它们是不同的。感谢您的帮助。

标签: javascript google-maps error-handling


【解决方案1】:

您正在检查它是否存在以创建变量,但您继续执行其余逻辑。你应该跳过它。

所以不是

if (data[i].Geocode_Latitude !== null) {
  let pot = {
    lat: la,
    lng: lo
  };
}

进行下一次迭代

for(...) {
  let la = data[i].Geocode_Latitude;
  let lo = data[i].Geocode_Longitude;
  if (la === null) { continue; }

【讨论】:

  • 感谢这个修复它Epascarello! @Andreas 我从使用 'null' 更改为 'undefined',这使它对我有用。我错误地假设 null 与 undefined 相同,谢谢。
  • 必须与 undefined 进行比较,因为响应中完全缺少属性。
猜你喜欢
  • 1970-01-01
  • 2017-10-09
  • 1970-01-01
  • 2012-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-28
相关资源
最近更新 更多