Ashwin Vivek
Ashwin Vivek

Reputation: 23

pass data from jQuery ajax GET request to google maps script

I have created an API that returns a json consisting of a latitude and longitude, and wanted to pass that into the Google Maps API, to get the corresponding map.

To get the data from my API I created an ajax request as follows:

scripts.js:

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

        //do something with this data

    });
  });
});

After I get the JSON from this, I want to pass the latitude and longitude to the script that Google Maps API provides as follows, inside my 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>

Basically, I want to be able to pass the latitude and longitude from my GET request to this script so that I can pass them into the google maps API call. I am fairly new to jQuery, so have no idea how to do this.

Thanks!

Upvotes: 1

Views: 1451

Answers (1)

Jeramiah Harland
Jeramiah Harland

Reputation: 864

Why not just pass the lat/lng as parameters to the 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>

You can move that initMap() function to scripts.js. Just make sure you're loading Google Maps API before your scripts.js.

Upvotes: 2

Related Questions