I am going to display location of company at google map according to user's address. By the way, The input address is different, but only the same address is displayed every time. Help me my code is follow.Thanks.
<!DOCTYPE html>
<html>
<body>
<h1>My First Google Map</h1>
<div id="googleMap" style="width:100%;height:400px;"></div>
<script>
function myMap() {
var address = "<?php echo $address;?>";
var latitude = 0;var longitude = 0;
//alert(address);
var geocoder = new google.maps.Geocoder();
//var address = document.getElementById(address).value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
alert("Latitude: " + latitude + "\nLongitude: " + longitude);
} else {
alert("Request failed.");
}
});
var mapProp= {
center:new google.maps.LatLng(latitude,longitude),
zoom:5,
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCY- jGtLHPdttTiekXaSPncp6haCA3VeLU&callback=myMap"></script>
</body>
</html>
Because geocoder.geocode
is asynchronous you won't have updated latitude
and longitude
before you use them, therefore your map center is 0,0
Initialise the map in the callback to geocoder.geocode
as follows
function myMap() {
var address = "<?php echo $address;?>";
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var mapProp = {
center: results[0].geometry.location,
zoom: 5,
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
} else {
console.error("Request failed.", status);
}
});
}
Note: in the code above I use
center: results[0].geometry.location,
to set the map centre, to avoid deconstructing the lat/long from aLatLng
object, only to create a newLatLng
object from the retrieved co-ordinates - seems a wasted effort :p
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.