我收到错误 Uncaught SyntaxError: Unexpected token : (dev.virtualearth.net/:1)
这是我的 JavaScript。
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browswer or not enabled.");
}
}
function showPosition(position) {
$.ajax({
url: 'http://dev.virtualearth.net/REST/v1/Locations/',
dataType: 'jsonp',
data: {
q: position.coords.latitude + ',' + position.coords.longitude,
key: '***'
}
}).then(function(data) {
//alert("Latitude: " + position.coords.latitude + "<br /> Longitude: " + position.coords.longitude +
//"<br /> Province: " + data.resourceSets.resources[0].address.locality);
console.log(data.toString());
});
}
返回的json是有效的,但不确定错误发生在哪里。
最佳答案
您的查询存在一些问题:
- 不应像您所做的那样将坐标传递到查询参数中。这不会像我认为您正在尝试做的那样为您反转地理编码位置。坐标应该是 URL 的一部分,例如 .../Location/latitude,longitude?key=
- 除了dataType之外,还要设置ajax方法的jsonp参数。
- 不要使用导航器,而是使用 GeoLocationProvider属于 Bing map API 一部分的类。较旧的浏览器不支持 Navigator 类,但是,某些较旧的浏览器确实有其他方法来获取用户位置。 GeoLocationProvider 类为您将所有这些不同的方法包装在一起。如果需要,您还可以选择显示精度圆并设置 map View 。
- 使用 REST 服务的 session key 而不是 Bing map key 。这将使该服务请求成为不可计费交易。
下面是一个代码示例,可让您获取用户位置并对其进行反向地理编码:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
var map, sessionKey;
function GetMap()
{
map = new Microsoft.Maps.Map(document.getElementById("myMap"), {
credentials: "YOUR_BING_MAPS_KEY"
});
map.getCredentials(function(c){
sessionKey = c;
});
}
function getLocation() {
var geoLocationProvider = new Microsoft.Maps.GeoLocationProvider(map);
geoLocationProvider.getCurrentPosition({
showAccuracyCirle: false,
updateMapView: false,
successCallback: showPosition
});
}
function showPosition(position) {
$.ajax({
url: 'http://dev.virtualearth.net/REST/v1/Locations/' + position.center.latitude + ',' + position.center.longitude,
dataType: "jsonp",
jsonp: "jsonp",
data: {
key:sessionKey
},
success: function (result) {
if (result &&
result.resourceSets &&
result.resourceSets.length > 0 &&
result.resourceSets[0].resources &&
result.resourceSets[0].resources.length > 0) {
alert(result.resourceSets[0].resources[0].address.formattedAddress);
}else{
alert("No Results Found");
}
},
error: function (e) {
alert(e.statusText);
}
});
}
</script>
</head>
<body onload="GetMap();">
<div id='myMap' style="position:relative;with:800px;height:600px;"></div><br/>
<input type="button" onclick="getLocation()" value="test"/>
</body>
</html>
关于javascript - Bing map API 请求返回 Uncaught SyntaxError : Unexpected token :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26408515/