Google Maps API Common Errors & Solutions

1. For Development Purposes Only

<script src="https://maps.googleapis.com/maps/api/js"></script>

Solution

<script src="https://maps.googleapis.com/maps/api/js?key=[YOUR_API_KEY]"></script>

2. Google Is Not Defined

<script>
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: {
lat: 45.4215296,
lng: -75.6971931
},
mapTypeId: google.maps.MapTypeId.ROADMAP
});
</script>

Solution

<script src="https://maps.googleapis.com/maps/api/js?key=[YOUR_API_KEY]"></script><script>
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: {
lat: 45.4215296,
lng: -75.6971931
},
mapTypeId: google.maps.MapTypeId.ROADMAP
});
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=[YOUR_API_KEY]&callback=initMap"></script><script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: {
lat: 45.4215296,
lng: -75.6971931
},
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=[YOUR_API_KEY]&callback=initMap"></script><script>
function initMap() {
}
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: {
lat: 45.4215296,
lng: -75.6971931
},
mapTypeId: google.maps.MapTypeId.ROADMAP
});
</script>

Solution

<script src="https://maps.googleapis.com/maps/api/js?key=[YOUR_API_KEY]"></script><script>
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: {
lat: 45.4215296,
lng: -75.6971931
},
mapTypeId: google.maps.MapTypeId.ROADMAP
});
</script>

3. CORS Error

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "https://maps.googleapis.com/maps/api/directions/json?origin=45.4215297, -75.6971932&destination=45.4215296, -75.6971931&key=[YOUR_API_KEY]", true);
xhttp.send();

Error

🛑  Access to XMLHttpRequest at 'https://maps.googleapis.com/maps/api/geocode/json?latlng=7.9411343,98.3942565&key=xxxxx from origin 'http://localhost:8080' has been blocked by CORS policy: Cross-origin requests are only supported for protocol schemes: HTTP, data, chrome, chrome-extension, https.

Solution

xhttp.open("GET", "https://cors-anywhere.herokuapp.com/https://maps.googleapis.com/maps/api/directions/json?origin=45.4215297, -75.6971932&destination=45.4215296, -75.6971931&key=[YOUR_API_KEY]", true);

4. This API Project Is Not Authorized To Use This API

Solution

5. You Must Enable Billing On The Google Cloud Project

Solution

Instructor/Owner of SoftAuthor! http://softauthor.com/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store