从地理编码对象获取纬度

时间:2011-10-24 15:27:24

标签: javascript html google-maps google-maps-api-3

我想从地理编码器返回的结果对象中获取纬度和经度。

<!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 个答案:

答案 0 :(得分:20)

您应该可以像这样访问各个值:

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