Вопрос

OK so I rad through the documentation however I still don't understand exactly how it works. If I want to search for a place I am supposed to use an HTTP get request to return json data. How do I do this using JavaScript? The documentation just shows me how to structure the HTTP request like so

https://maps.googleapis.com/maps/api/place/nearbysearch/output?parameters

But how do I then send this request? Pointing me to a tutorial or something would be great.

Это было полезно?

Решение

The Places Library does all the work. You only have to send the fields you require and then display Place Details Results

The following code is taken from the documentation to show you where to add to it to implement your preferences.

var map;
var service;
var infowindow;

function initialize() {
  var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);

  map = new google.maps.Map(document.getElementById('map'), {
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: pyrmont,
      zoom: 15
    });
 //Here you add the fields you require for request for PlacesService() 
  var request = {
    location: pyrmont,
    radius: '500',
    types: ['store']
  };

  service = new google.maps.places.PlacesService(map);
  service.nearbySearch(request, callback);
}
  //Here you display the Place Details Results
function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      var place = results[i];
      createMarker(results[i]);
    }
  }
}

Другие советы

Short version: Write an AJAX call to get the data, then write a callback function to do something with that data.

Long version:

Ajax Requests

Ajax requests are HTTP requests made from within the webpage, such that the page does not perform any navigation action. These are used to do things like grab data from APIs (like what you are trying to do) or load images, load additional page content, etc. etc.

In your case, you want to perform a simple AJAX request to the API URL, and then do something with the data you get back.

Since you sound like you're new to the realm of JavaScript I highly recommend using the jQuery JavaScript library. It makes things such as Ajax a walk in the park. Specifically, you can use the jQuery.Ajax() function to build your web request. You then specify the callback function that you pass your API data to, and do something with it.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top