将Google Maps Elevation json字符串放入变量中

时间:2015-09-02 18:03:02

标签: google-maps

根据this page,如果我插入this url into my browser,那么我得到一个很好的json字符串。

问:如何将json字符串转换为JavaScript变量?

我是否会这样做:

var x = location('https://maps.googleapis.com/maps/api/elevation/json?locations=39.7391536,-104.9847034')

2 个答案:

答案 0 :(得分:1)

要获取json,您必须使用jquery创建一个ajax请求,例如$ .get('url')。不幸的是,您将遇到跨域问题。

但您可以使用the google maps javascript API

var init = function() {
  var elevator = new google.maps.ElevationService;
  elevator.getElevationForLocations({      
    'locations': [new google.maps.LatLng(39.7391536,-104.9847034)]
    }, function(results, status) {
        if (status === google.maps.ElevationStatus.OK) {
          if (results[0]) {
            $("#result").text('elevation: ' + JSON.stringify(results[0]))
          }
        }
    })
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?signed_in=true&callback=init"
        async defer>
</script>
<div id="result"></div>

答案 1 :(得分:1)

function currentPosition(arg) {
    var svc = new google.maps.ElevationService
    var param = {}
    param.locations = []
    param.locations[0] = new google.maps.LatLng(arg.coords.latitude,arg.coords.longitude)
    svc.getElevationForLocations(param, elevationForLocations)
}
function elevationForLocations(argResponse, argStatus) {
    if (argStatus === google.maps.ElevationStatus.OK) {
        var response = argResponse[0] // https://developers.google.com/maps/documentation/javascript/elevation?hl=en
        if (response) {
            $("#result").text(JSON.stringify(response))
            $('#elevation').text(response.elevation)
            $('#location').text(JSON.stringify(response.location))
            $('#G').text(response.location.G)
            $('#K').text(response.location.K)
            $('#resolution').text(response.resolution)
        }
    }
}
navigator.geolocation.getCurrentPosition(currentPosition);