百度座標轉換API使用

鬆門一枝花發表於2016-05-05

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=sGSOaO07WkRHHiCRxxbSQVBn
	var 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=sGSOaO07WkRHHiCRxxbSQVBn
	var 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>





相關文章