在 Javascript 中异步获取给定坐标附近的地标



我需要在经纬度定义的位置周围的重要场所(如医院,学校,商店等(。我在PHP中成功实现了它,如下所示:

$lat = "27.71158601970849";
$lon = "85.3187467697085";
$type = "hospital";
$json = json_decode(file_get_contents("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$lon&radius=1000&type=$type&key=AIzaSyBeeGuG4sYloXT54VJZ5JeADQ8DmG9toBc") , true );

使用变量$json信息,我可以显示附近的地方。

我注意到,当我需要为每个属性类型(医院、学校等(循环运行相同的代码时,我的page load time increased to 7 seconds.这显然是访客不希望的。

所以为了让用户体验更好,我认为使用 ajax 调用会更好。所以我尝试了这段代码:

$(document).ready(function(){
if(typeof latitude !== typeof undefined){
var lat = latitude;
var lon = longitude;
var type = "hospital";
$.ajax({
type:"GET",
url:"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="+lat+","+lon+"&radius=1000&type="+type+"&key=AIzaSyBeeGuG4sYloXT54VJZ5JeADQ8DmG9toBc&callback?",
dataType:"json",
crossDomain: true,
contentType: "application/json; charset=utf-8;",
// async: true,
success: function(results){
console.log(results);
},
error: function (xhr, textStatus, errorThrown) {
console.log('Error in Operation');
console.log(xhr);
console.log(textStatus);
console.log(errorThrown);
},
jsonpCallback: function(result)
{ 
console.log(result); 
}
});
// console.log(latitude , longitude);
}
});

我已经陷入这个问题 3 天了。互联网上没有解决方案有效。我在控制台中得到以下输出。

Warning: 

跨源请求被阻止:同源策略不允许读取 位于的远程资源 https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=27.717807854017007,85.32777655029304&radius=1000&type=hospital&key=AIzaSyBeeGuG4sYloXT54VJZ5JeADQ8DmG9toBc&callback?。 (原因:缺少 CORS 标头"访问控制-允许源"(。

许多解决方案建议将服务器端标头更改为Access-Control-Allow-Origin *。但是如何更改谷歌API的服务器端代码呢?为什么在同一站点的 PHP 中解码相同的响应而没有错误?

Error in Operation
parsererror
SyntaxError: unexpected token: ':'[Learn More]

我在控制台中得到一个JSON 文件,我不知道它从哪里显示,但它是我需要的 json,但该文件中有错误。要自己查看问题,您可以访问我的网站

json 文件如下所示:

{
"html_attributions" : [],
"next_page_token" : "CvQD5QEAAKjJw1utsQJW5CkIGPIFiu-3qtZEZs_MTNBiGLQnTWR3Z_8GTrtQ06cq_2x9TFtRunS-ZTswJQegZmB2A4d42ML0NBqkHqrZkQy4doNCeRY2f3A_7RKPzSHqIMhrfHr75LhVhAylbiwb9ee_og9pm7mRnLAXRC3FkyTCnRH8gz_Ef3Zfr39NOyVwYDUP5uDy_YW425Um_WA4KSuasuc8sxQlb5QlWW9Ol9Zd6MtEanWcPGoCeabJQRuwQjMqM78eokRYfo_pyVsd_duVn7r0Np4WXvETSpwjLQwSW7E34O9o3xAB7_Kjx9qkQRGiLrYpuzqCLZaUaliQ1K00sScWmNbsnTOyrmQf1pqzkQkCwsEILherFOJLVCxyEXGN9Pa1C9gZfJhR7KOVcDW__BIo7n0mcps1JO4GEMgNpbULpQMRGSGdT3-2vtOITQJYzvPtnpYewvyEJtLvJOTX3_f-VqYG1OAbArH6riGJ1kYXTQN4ZX6w2LbiEWDRKCEr50RuHnRstvbfv-O74yfJUhrnYsI14b2XtFSQGADPIJqBCcqUHUSx5li2BF8f5da3IcmZVjKHGn-2dozfVYE190aIDYYYcwqGNWJIjE20fnwaR6302mFzJ8ssHL2liDzcpAxcrWjfVdM86riwWBhEPmIyKUMSENYZmjWNGgkpGJbRElNeyoAaFJ2QH902uDsBeXzEGM9tBSe9OWVZ",
"results" : [
{
"geometry" : {
"location" : {
"lat" : 27.718038,
"lng" : 85.32124039999999
},
"viewport" : {
"northeast" : {
"lat" : 27.7193869802915,
"lng" : 85.3225893802915
},
"southwest" : {
"lat" : 27.71668901970849,
"lng" : 85.31989141970848
}
}
},
"icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/doctor-71.png",
"id" : "38f6d1f517223601b130cc35bdf6bfb95b205ef5",
"name" : "Dental Imaging Centre",
"opening_hours" : {
"open_now" : true,
"weekday_text" : []
},
"photos" : [
{
"height" : 3480,
"html_attributions" : [
"u003ca href="https://maps.google.com/maps/contrib/116325705698031818585/photos"u003eSangam Dhakalu003c/au003e"
],
"photo_reference" : "CmRaAAAA6u3e7yL6fwG77PVsWJN07knD6jmQMa2dRL7vmtToFh9x6KaViDf2WHhYtiYPacZTlzCAB2npe8z45hR18UbQfrTRCLXt2wAPHGYLNRqGD7zwfuPRETZ0nh5nIlr72VAlEhDItbx5uxo24kxLQ0_CT29ZGhTvzKiIkyyyRSfF8bjlKVsz_Csjjw",
"width" : 4640
}
],
"place_id" : "ChIJheuuJxsZ6zkRlgeZX3mXoMI",
"rating" : 4,
"reference" : "CmRSAAAATXt4gZlyejOUAKP4DL2ECCIGIC7cCxxiQv03oA7IdSKZ1OpP1HPyoTG37IuJ3xZyavW3G4H5eEiavjJKwIAss8yM6xIeDla_FdDnrM6NhbOzJ5FaH0uufIcAHGtxBkBsEhB4RdTC6Zvx9nnHecH7s4snGhQpfzxe5vDMtigmAoPQ_cDN-xZO1g",
"scope" : "GOOGLE",
"types" : [ "hospital", "point_of_interest", "establishment" ],
"vicinity" : "Kathmandu"
}
...
...

谷歌的官方文档。

我最终从谷歌地图javascript API文档中找到了解决方案,该解决方案非常有效,只是不要忘记在完全加载后绑定一个事件以运行此代码到文档。

function initMap() {
console.log('latit',latitude);
var myLatLng = {lat: latitude, lng: longitude};
var map1 = new google.maps.Map(document.getElementById('map_detail'), {
zoom: 15,
center: myLatLng
});
var marker1 = new google.maps.Marker({
position: myLatLng,
map: map1,
});
service = new google.maps.places.PlacesService(map1);
Object.keys(nearbyLandmarksArr).forEach(function(key) {
var request = {
location: myLatLng,
radius: '1000',
query: key
};  
service.textSearch(request, callback);
// console.log(key, obj[key]);
});
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) { 
for (var i = 0; i < results.length; i++) {
console.log( results[i] , place.types);
}
}
}

以下行在加载后将上面的代码与 DOM 绑定。

google.maps.event.addDomListener(window, 'load', initMap);

相关内容

  • 没有找到相关文章

最新更新