I am trying to learn how to use the Google geocoding API but I cannot seem to make even the simplest example produce a map. I have searched on Google for alternative tutorials but everything seems in order.
Obviously I must be missing something. Here is what I have so far :
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=thisstuffisprivate&sensor=false">
</script>
<script>
var map;
var mapOptions;
function initialize() {
try {
document.write("Initialize entered");
mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
document.write("<br>Map options created");
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
document.write("<br>Initialize exited");
} catch (err) {
document.write("<br>Error: " + err.message);
}
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:500px;height:300px;">
</div>
</body>
</html>
This produces a blank page. Note that I using this code on my computer and checking the results with Firefox. This is not hosted on an external server yet.
Can anybody help me figure out what mistake I have made ? This will enable me to continue learning how to use this API !
Thank you so much !
Edit:
– I have made a small test adding writes at the beginning and at the end of initialize() and it seems that it does not reach the last line (after the map creation) so it must be failing somewhere. Will try to investigate that.
-
Modified to take into account width and height. Thanks to Leftium.
-
After further testing, it seems to fail on the map creation step.
-
The code does not work on my computer on either IE, Firefox or Chrome but seems to work for other users. I am using Windows 8 and a relatively recent version of all browsers. Javascript IS enabled and I have tried turning off Windows Defender (just in case..). Still only a blank page.
-
I have also used an API key but it still produces a blank page.
-
I get the following output for the updated code above:
Initialize entered
Map options created
Error: a is null
- It also produces a blank page on my Windows 7 laptop so it’s not an issue of compatibility with Windows 8.
With further testing I found the exact error message and a solution on another SO question. Essentially, the problem is that the div is actually not fully built and the initialize() call searches for this element before it is in the DOM (please forgive me if the nomenclature is wrong).
The solution is to move the call lower below creating the div.
Google MAP API Uncaught TypeError: Cannot read property 'offsetWidth' of null