http://api.map.baidu.com/geoconv/v1/?coords=121.54759,29.870724&from=1&to=5&ak=sGSOaO07WkRHHiCRxxbSQVBn
前提:121.54759,29.870724 是由手机硬件或谷歌地图获取的
错误的方法一:
function standard2china(lng,lat){//http://api.map.baidu.com/geoconv/v1/?coords=121.54759,29.870724&from=1&to=5&ak=sGSOaO07WkRHHiCRxxbSQVBnvar apiurl="http://api.map.baidu.com/geoconv/v1/?coords="+lng+","+lat+"&from=1&to=5&ak=sGSOaO07WkRHHiCRxxbSQVBn";$.ajax({url:apiurl,type:'get',success:function(data){console.log(data);}});
}
会提示错误:No 'Access-Control-Allow-Origin' header is present on the requested resource.
这是跨域问题,见:http://blog.csdn.net/zengmingen/article/details/51321758
错误方法二:
知道了跨域问题,解决要用dataType:'jsonp'
function standard2china(lng,lat){//http://api.map.baidu.com/geoconv/v1/?coords=121.54759,29.870724&from=1&to=5&ak=sGSOaO07WkRHHiCRxxbSQVBnvar apiurl="http://api.map.baidu.com/geoconv/v1/?coords="+lng+","+lat+"&from=1&to=5&ak=sGSOaO07WkRHHiCRxxbSQVBn";$.ajax({url:apiurl,type:'get',dataType:'jsonp',success:function(data){console.log(data);}});
}
不提示报错,但是返回结果是百度的js文件内容:
正确方法:
百度demo:http://developer.baidu.com/map/jsdemo.htm#a5_2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=sGSOaO07WkRHHiCRxxbSQVBn"></script><script type="text/javascript">abc();function abc(){var x = 121.5473;var y = 29.87061;var ggPoint = new BMap.Point(x,y);var convertor = new BMap.Convertor();//坐标转换完之后的回调函数translateCallback = function (data){if(data.status === 0) {for (var i = 0; i < data.points.length; i++) {var newPoint=data.points[i]; console.log(newPoint.lng);console.log(newPoint.lat);}}}setTimeout(function(){var convertor = new BMap.Convertor();var pointArr = [];pointArr.push(ggPoint);convertor.translate(pointArr, 1, 5, translateCallback);}, 1000);}</script></head><body></body>
</html>