2

我使用纬度和经度在谷歌地图中显示用户地址。我通过使用 java 脚本获得了纬度和经度,并且还有地图脚本。但我不知道如何组合它们,我需要的只是将经纬度传递到显示地图脚本“函数初始化()”中。这是我的代码:

<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>
4

1 回答 1

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>

工作示例

于 2013-09-21T18:47:58.927 回答