问题
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