从地理编码对象中获取纬度

3
我想从geocoder返回的结果对象中获取纬度和经度。
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Smart Minds</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
  var geocoder;
  var map;
  function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 4,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  }

  function codeAddress() {
    var address = document.getElementById("address").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });



        var inp=results[0].geometry.location;


        alert(inp);
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }
</script>
</head>
<body onLoad="initialize()">


  <!--</div>-->
<!--<div id="map_canvas" style="height:80%;top:30px;right:40%;left:20%"></div>-->
 <div id="map_canvas" style="border-width:0;width:500px;height:500px;left:40px;right:60px;top:20px"></div>

  <input id="address" type="textbox" value="" style="margin-top:60px;margin-left:400px;" placeholder="Enter your Location">
    <input type="button" value="Get me There" onClick="codeAddress()">
</body>
</html>

results[0].geometry.location 包含了经度和纬度,但我想要单独获取经度和纬度的值。我曾试图在 results[0].geometry.location 上使用像 split() 和 slice() 这样的javascript函数,但这并不起作用。请问有谁能告诉我如何做到这一点呢?

1个回答

21

你应该能够像这样访问各个值:

var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();

3
尝试使用 lat()lng()。它们可以帮助你获取经纬度信息。 - justkt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接