【问题标题】:pass data from jQuery ajax GET request to google maps script将数据从 jQuery ajax GET 请求传递到谷歌地图脚本
【发布时间】:2017-07-20 16:24:24
【问题描述】:

我创建了一个 API,它返回一个由纬度和经度组成的 json,并希望将其传递给 Google Maps API,以获取相应的地图。

为了从我的 API 中获取数据,我创建了一个 ajax 请求,如下所示:

scripts.js:

$(document).ready(function(){
  $("button").click(function(){
    $.get("my url", function(data, status){

        //do something with this data

    });
  });
});

从这里获得 JSON 后,我想将纬度和经度传递给 Google Maps API 在我的 index.html 中提供的脚本,如下所示。

index.html

<body>
  <h1> JOS Map App </h1>
  <button>Send an HTTP GET request to a page and get the result back</button>
  <script type="text/javascript" src = "js/jquery-3.2.1.min.js"></script>
  <script type="text/javascript" src = "js/scripts.js"></script>
  <div id="map"></div>
    <script>  //THIS ONE!!
      function initMap() {
        var uluru = {lat: , lng: };
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 4,
          center: uluru
        });
        var marker = new google.maps.Marker({
          position: uluru,
          map: map
        });
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
</body>

基本上,我希望能够将我的 GET 请求中的纬度和经度传递给这个脚本,以便我可以将它们传递给 google maps API 调用。我对 jQuery 还很陌生,所以不知道该怎么做。

谢谢!

【问题讨论】:

    标签: javascript jquery json ajax google-maps


    【解决方案1】:

    为什么不将 lat/lng 作为参数传递给 Google Maps init()?

        <script>
    
        $(document).ready(function(){
          $("button").click(function(){
            $.get("my url", function(data, status){
    
                initMap(data.lat, data.lng);
    
            });
          });
        });
    
        function initMap(lat, lng) {
           var uluru = {lat: lat, lng: lng};
           var map = new google.maps.Map(document.getElementById('map'), {
              zoom: 4,
              center: uluru
           });
           var marker = new google.maps.Marker({
              position: uluru,
              map: map
           });
         }
      </script>
    

    您可以将该 initMap() 函数移至 scripts.js。只需确保在您的 scripts.js 之前加载 Google Maps API。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-12
      • 1970-01-01
      • 1970-01-01
      • 2017-07-20
      • 2021-04-03
      • 1970-01-01
      • 1970-01-01
      • 2012-05-03
      相关资源
      最近更新 更多