passing the latitude and longitude to my map script

ε祈祈猫儿з 提交于 2020-01-05 04:00:49

问题


I show the user address in the google map by using the latitude and longitude. I got the lat & long by using an java-script, and also have the map script. but I dont know how to combine them, Simply what I need is pass the lat and long into the show map script "function initialize()". this is my code:

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


Geocode the address in your initialize function. Use the returned latitude and longitude to initialize the map.

<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



来源:https://stackoverflow.com/questions/18936231/passing-the-latitude-and-longitude-to-my-map-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!