Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

javascript - Google's Places API and JQuery request - Origin http://localhost is not allowed by Access-Control-Allow-Origin

I doing some testing for a project I got in mind which involves using places nearby. So I went with the big guy and started messing around with Google's Places Api. I'm using leaflet with openstreet tiles for my map. Now everything is fine until I try to use the dang thing.

var lat = coords.lat;
var lng = coords.lng;
var apiUrl = "https://maps.googleapis.com/maps/api/place/nearbysearch/json";
var data = {
    key: 'AIzaSyBl8bmE8kQT7RjoXhP6k2yDti44h9-fSUI',
    location: lat+','+lng,
    radius: '10000',
    sensor: 'false',
    rankby: 'prominence',
    types: 'bar|night_club'
};
$.ajax({
  url: apiUrl,
  type: 'POST',
  data: data,    
  dataType:"jsonp",
  crossDomain: true,
  success: function(data) {
            var obj = $.parseJSON(data);
                // console.log(data.next_page_token);
          }
});

Changing the dataType property to json I get Origin http://localhost is not allowed by Access-Control-Allow-Origin. Using jsonp I get a parsing error Unexpected token : Obviusly $.parseJSON does not work... Is there a way to make this work without having to use Google Maps Api? If the answer is no... Is there another places api as good as google's?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're trying to use the Places API web service, which is meant for use from server code and does not support the JSONP output you'd need for JavaScript.

In JavaScript, you need to use the Places Library from the Maps API V3. You can't just hit a URL directly from JavaScript or jQuery code. (You could probably discover the URL pattern that the Places Library uses, but the terms of service don't allow direct use without going through the API/Library, and the URL could change at any time.)

Is there a reason you don't want to use the Maps API from JavaScript?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...