understand the google places api for using with a webpage

自古美人都是妖i 提交于 2019-12-08 08:01:57

问题


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.


回答1:


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]);
    }
  }
}



回答2:


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.

  • Ajax information
  • Callback information


来源:https://stackoverflow.com/questions/13325946/understand-the-google-places-api-for-using-with-a-webpage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!