更新时间:2023-11-06 23:07:16
This will change the codeAddress function to take an argument and geocode that argument. If you pass the Ireland variable as the argument it will geocode "Dublin".
var Ireland = "Dublin";
function initialize()
{
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(53.3496, -6.3263);
var mapOptions =
{
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
codeAddress(Ireland);//call the function
}
function codeAddress(address)
{
geocoder.geocode( {address:address}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.location);//center the map over the result
//place a marker at the location
var marker = new google.maps.Marker(
{
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
code snippet:
var Ireland = "Dublin";
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(53.3496, -6.3263);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
codeAddress(Ireland); //call the function
}
function codeAddress(address) {
geocoder.geocode({
address: address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location); //center the map over the result
//place a marker at the location
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
html,
body,
#map-canvas {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
}
<div id="map-canvas"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initialize" async defer></script>