Sharpzain120
Sharpzain120

Reputation: 375

Getting Latitude from Geocode Object

I want to get the latitude and longitude from the result object returned by 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>

The results[0].geometry.location contains both the latitude and the longitude but I want to get separate values of longitude and latitude. I had tried to use a javascript function like split() and slice() on results[0].geometry.location but that is not working. Can anyone please tell me how I can do that?

Upvotes: 3

Views: 10184

Answers (1)

Beor
Beor

Reputation: 399

You should be able to access the individual values like this:

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

Upvotes: 21

Related Questions