I have done a simple GoogleMap which responses to script.php?q=canada and shows a map.
One problem is it always loads the map with the center var latlng = new google.maps.LatLng(34.052234,-118.243685); for a second and then loads the right map.
What’s wrong with my code?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title><?=$_GET['q']?></title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(34.052234,-118.243685);
var address = '<?=$_GET['q']?>';
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
// autozoom
map.fitBounds(results[0].geometry.viewport);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: 'by Quick Maps',
clickable: false
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
</body>
</html>
Sidequestion:
how to replace alert("Geocode was not successful for the following reason: " + status); with a simple message on the map?
The quick answer is to move the map instantiation into the geocode callback.
That would prevent the map from displaying centered around 34.052234,-118.243685.
About the user experience when no results are returned, you could hide the map and display some text, for example?
But what you want to do here should be highly dependent on the general user interface of your solution 🙂