将数据从jQuery ajax GET请求传递到谷歌地图脚本

时间:2017-07-20 16:24:24

标签: javascript jquery json ajax google-maps

我创建了一个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之后,我想将经度和经度传递给我在index.html中提供的Google Maps API提供的脚本。

的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>
&#13;
&#13;
&#13;

基本上,我希望能够将我的GET请求中的纬度和经度传递给此脚本,以便我可以将它们传递到google maps API调用中。我对jQuery很新,所以不知道如何做到这一点。

谢谢!

1 个答案:

答案 0 :(得分: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。