将纬度和经度传递给我的地图脚本

时间:2013-09-21 18:42:18

标签: javascript google-maps google-api

我使用纬度和经度显示谷歌地图中的用户地址。我得到了lat&通过使用java脚本,并具有映射脚本。但我不知道如何组合它们,简单地说我需要的是将lat和long传递给show map脚本“function initialize()”。这是我的代码:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
var geocoder;
var centerChangedLast;
var reverseGeocodedLast;
var currentReverseGeocodeResponse;

var geocoder = new google.maps.Geocoder();
var address = "<?php echo $address;?>";

geocoder.geocode( { 'address': address}, function(results, status) {

  if (status == google.maps.GeocoderStatus.OK) {
    var latitude = results[0].geometry.location.lat();
    var longitude = results[0].geometry.location.lng();
    //alert(longitude);
  } 
});     

function initialize() {

    var latlng = new google.maps.LatLng(latitude,longitude);
    var myOptions = {
        zoom: 10,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    geocoder = new google.maps.Geocoder();

    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        title: "My Location"
    });

}

</script>

1 个答案:

答案 0 :(得分:3)

在初始化函数中对地址进行地理编码。使用返回的纬度和经度初始化地图。

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
var geocoder;
var centerChangedLast;
var reverseGeocodedLast;
var currentReverseGeocodeResponse;

var geocoder = new google.maps.Geocoder();
var address = "<?php echo $address;?>";


function initialize() {
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      var latitude = results[0].geometry.location.lat();
      var longitude = results[0].geometry.location.lng();
      var latlng = new google.maps.LatLng(latitude,longitude);
      var myOptions = {
        zoom: 10,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
      geocoder = new google.maps.Geocoder();

      var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        title: "My Location"
      });

    } 
  });
}

</script>

working example