Google Maps Javascript API not loading correctly - javascript

I am trying to load Google Maps API in a webpage with the <script> tags at the bottom of the body with the #map element referenced above.
Get the error alert: "This page was unable to display a Google Maps element. The provided Google API key is invalid or this site is not authorized to use it. Error Code: InvalidKeyOrUnauthorizedURLMapError"
My API KEY is definitely correct; I have checked it multiple times.
I have chosen to accept request from the following referrers
*.mywebsite.com/*
*.mywebsite.com*
www.mywebsite.com/*
www.mywebsite.com/test // this is the url I am trying to load the map on.
I have tried without the API Key Reference and without the Init callback and the map loads intermittently. Sometimes it will load (around 20% of the time), other times it doesn't and I get the following console log - ReferenceError: google is not defined;
<script async defer src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&callback=initMap"></script>
<script src="/js/map.js"></script>
My map.js file containing the map config
var map;
var mapLatLng = {lat: 13.778182, lng: -0.23676};
var mapStyle = [maps style options] // https://snazzymaps.com/style/38/shades-of-grey
var mapMarker = '/img/marker.png';
function initMap() {
var styledMap = new google.maps.StyledMapType(mapStyle,
{name: "Styled Map"});
var mapOptions = {
center: mapLatLng,
zoom: 10,
scrollwheel: false,
navigationControl: false,
mapTypeControl: false,
scaleControl: false,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
}
};
var map = new google.maps.Map(document.getElementById('map'),
mapOptions);
var marker = new google.maps.Marker({
position: mapLatLng,
map: map,
title: 'Hello World!',
icon: mapMarker
});
//Associate the styled map with the MapTypeId and set it to display.
map.mapTypes.set('map_style', styledMap);
map.setMapTypeId('map_style');
}
google.maps.event.addDomListener(window, 'load', initMap);

You call the GMap script as async defer, so you are not sure that the script will be downloaded and executed before map.js. And your map.js script call the GMap API.
Could you test first without the async defer attribute. If it's ok, just move all your initialization code in the initMap function, it should work :
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var marker = new google.maps.Marker({
position: mapLatLng,
map: map,
title: 'Hello World!',
icon: mapMarker
});
//Associate the styled map with the MapTypeId and set it to display.
map.mapTypes.set('map_style', styledMap);
map.setMapTypeId('map_style');
var styledMap = new google.maps.StyledMapType(mapStyle, {name: "Styled Map"});
var mapOptions = {
center: mapLatLng,
zoom: 10,
scrollwheel: false,
navigationControl: false,
mapTypeControl: false,
scaleControl: false,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
}
};
}

Related

logading google maps script asynchronously

I am attempting to load my google maps api call script asynchronously so its not render blocking on my WordPress Site.
Disregard the PHP, I am loading in custom settings through the customizer.
I am able to load it by adding async defer to my api call script tag but the problem is that the map only loads when I hard-reload the browser, the average user will not know to do that. How can i make the map load without requiring to hard reload the site?
<script id="map-code" type="text/javascript" async defer>
function init() {
var styledMapType = new google.maps.StyledMapType([{"elementType":"geometry","stylers":[{"color":"#f5f5f5"}]},{"elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"elementType":"labels.text.fill","stylers":[{"color":"#616161"}]},{"elementType":"labels.text.stroke","stylers":[{"color":"#f5f5f5"}]},{"featureType":"administrative.land_parcel","elementType":"geometry.stroke","stylers":[{"color":"#c7e0ba"}]},{"featureType":"administrative.land_parcel","elementType":"labels.text.fill","stylers":[{"color":"#bdbdbd"}]},{"featureType":"poi","elementType":"geometry","stylers":[{"color":"#eeeeee"}]},{"featureType":"poi","elementType":"labels.text.fill","stylers":[{"color":"#757575"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#e5e5e5"}]},{"featureType":"poi.park","elementType":"labels.text.fill","stylers":[{"color":"#9e9e9e"}]},{"featureType":"road","elementType":"geometry","stylers":[{"color":"#ffffff"}]},{"featureType":"road.arterial","elementType":"labels.text.fill","stylers":[{"color":"#757575"}]},{"featureType":"road.highway","elementType":"geometry","stylers":[{"color":"#dadada"}]},{"featureType":"road.highway","elementType":"labels.text.fill","stylers":[{"color":"#616161"}]},{"featureType":"road.local","elementType":"labels.text.fill","stylers":[{"color":"#9e9e9e"}]},{"featureType":"transit.line","elementType":"geometry","stylers":[{"color":"#e5e5e5"}]},{"featureType":"transit.station","elementType":"geometry","stylers":[{"color":"#eeeeee"}]},{"featureType":"water","elementType":"geometry","stylers":[{"color":"#c9c9c9"}]},{"featureType":"water","elementType":"labels.text.fill","stylers":[{"color":"#9e9e9e"}]}] , {name: "Styled Map"});
var position = [<?php echo get_theme_mod('google_map_coordinates') ?>];
var latLng = new google.maps.LatLng(position[0], position[1]);
var mapOptions = {
zoom: 11, // initialize zoom level - the max value is 21
streetViewControl: false, // hide the yellow Street View pegman
scaleControl: true, // allow users to zoom the Google Map
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
fullscreenControl: false,
scaleControl: false,
center: latLng
};
var numberMarkerImg = {
url: '<?php echo get_theme_mod('map_marker_image')?> ',
size: new google.maps.Size(<?php echo get_theme_mod('map_marker_container_size') ?>),
scaledSize: new google.maps.Size(<?php echo get_theme_mod('map_marker_container_size') ?>),
labelOrigin: new google.maps.Point(<?php echo get_theme_mod('map_marker_label_position') ?>)
};
map = new google.maps.Map(document.getElementById('googlemaps'), mapOptions);
marker = new google.maps.Marker({
position: latLng,
label: 'Label',
map: map,
draggable: false,
animation: google.maps.Animation.DROP,
mapTypeControlOptions: {
mapTypeIds: ['styled_map']
},
title:"Your Name",
label: {
color: "<?php echo get_theme_mod('map_label_color') ?>",
text: "<?php echo get_theme_mod('google_label_name')?>",
fontWeight: "900",
fontSize: "16px"
},
icon: numberMarkerImg
});
map.mapTypes.set('styled_map', styledMapType);
map.setMapTypeId('styled_map');
}
//google.maps.event.addDomListener(window, 'load', init);
</script>
My script tag for the call
<script src="https://maps.googleapis.com/maps/api/js?callback=init&libraries=places&key=API_KEY" async defer></script>
I have tried putting the call above and below the map code without success. I mean the JS is successfully loaded in an async fashion but will not render without hard reload. I guess i need to know if I need to load them both asyn or defer or just the api call, im at the end of my witts.
Just do one small change & it works.
Remove callback=init from
<script src="https://maps.googleapis.com/maps/api/js?callback=init&libraries=places&key=API_KEY" async defer></script>
And call it from body tag,
Ex.<body onLoad="init();">

this.remove is not a function when removing Google Maps Overlay

I have an overlay placed on a google map:
function CustomerMarker(map) {
this.Map = map;
this.setMap(map);
}
GoogleMap = new google.maps.Map(document.getElementById("map"), {
zoom: 16,
canZoom: false,
center: { lat: lat, lng: lng },
mapTypeControl: false,
streetViewControl: false,
scaleControl: false,
clickableIcons: false
});
CustomMarker.prototype = new google.maps.OverlayView();
CustomMarker.prototype.onAdd = function () {
//Some code
};
CustomMarker.prototype.draw = function () {
//Some code
};
CustomMarker = new CustomMarker(GoogleMap);
Which works fine, and the overlay shows up, however is issue arises when I try to remove that
CustomMarker.setMap(null)
I get an error and the marker remains
Error: this.remove is not a function
pz#https://maps.googleapis.com/maps-api-v3/api/js/30/1/overlay.js:1:251
rk#https://maps.googleapis.com/maps-api-v3/api/js/30/1/overlay.js:2:476
_.pg.prototype.map_changed/<#https://maps.googleapis.com/maps/api
/js?key=AIzaSyBCiIPv6fgrRVn3veTJeP6ihfhrw8AXwbY:125:662
_.G#https://maps.googleapis.com/maps/api/js?key=AIzaSyBCiIPv6fgrRVn3veTJeP6ihfhrw8AXwbY:51:447
_.pg.prototype.map_changed#https://maps.googleapis.com/maps/api/js?key=AIzaSyBCiIPv6fgrRVn3veTJeP6ihfhrw8AXwbY:125:636
Db#https://maps.googleapis.com/maps/api/js?key=AIzaSyBCiIPv6fgrRVn3veTJeP6ihfhrw8AXwbY:37:103
_.k.set#https://maps.googleapis.com/maps/api/js?key=AIzaSyBCiIPv6fgrRVn3veTJeP6ihfhrw8AXwbY:101:728
_.jd/<#https://maps.googleapis.com/maps/api/js?key=AIzaSyBCiIPv6fgrRVn3veTJeP6ihfhrw8AXwbY:55:317
The documentation for OverlayView states:
You must implement three methods: onAdd(), draw(), and onRemove().
I don't see an implementation for onRemove.

Modernizr is not defined

I've included the Modernizr Touch Events detection to my project (only left the rest out to keep it light as possible).
I use it to set different Google Maps JS options as following:
<script>
function initMap() {
var myLatLng = {lat: 52.022322, lng: 4.209055};
if( Modernizr.touchevents ) {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
disableDefaultUI: false,
center: myLatLng,
scrollwheel: true,
draggable: false,
});
} else {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
disableDefaultUI: false,
center: myLatLng,
scrollwheel: false,
draggable: true,
});
}
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Duijnisveld Kasconstructies',
});
}
</script>
I've included this script in my page-contact.php file which displays the contact page on my Wordpress project.
Whenever I view the page I see no map and note the following error in my console:
(index):235 Uncaught ReferenceError: Modernizr is not defined
What am I missing here?
Thanks guys!
You are calling Modernizr before theme-min.js which is where you are defining it.
You should move your code below this line.
<script type="text/javascript" src="http://duijnisveld.wpengine.com/wp-content/themes/duijnisveld-kascontructies/scripts/min/theme-min.js?ver=4.5.3"></script>

Google maps API (using gmapsjs), setCenter throws "undefined is not a function"?

I'm try to set map center using gmapjs. When I resize the window I get:
Uncaught TypeError: undefined is not a function
Here the map and the listener for the resize event:
$(function () {
var holder = $('#map-property'),
lat = 46.534820,
lng = 13.024809;
var map = new GMaps({
div: '#'+holder.attr('id'),
lat: lat,
lng: lng,
zoom: 14,
scrollwheel: false,
panControl : false,
streetViewControl: false,
mapTypeControl: false,
draggable: true,
disableDoubleClickZoom: true,
zoomControlOptions:{
style:google.maps.ZoomControlStyle.SMALL
}
})
.addMarker({
lat: 46.534820,
lng: 13.024809,
title: 'Da Matteo',
icon: "/img/gmaps-marker.png"
});
$(window).on('resize', function() {
map.setCenter(lat, lng); // here is the error!
});
});
AFAIK the setCenter function is:
this.setCenter = function(lat, lng, callback) {
this.map.panTo(new google.maps.LatLng(lat, lng));
if (callback) {
callback();
}
};
The problem is, map = new Gmaps().addMarker() returns a marker object, not a map. Therefore it has no setCenter method.
You can do something like:
var map = new Gmaps({...})
map.addMarker({...})
Then write the event.

re initialize gmap3 map

Is it possible to re initialize a gmap3 map to its default settings (lat, long, zoom etc)?
I tried destroy on the map and then re run the initialise but it is not working.
See my jsfiddle here - http://jsfiddle.net/vlowe/z9dDE/1/
Wrap the map element in a container div, and then when you want to reset the map, just remove the whole map div and recreate it. This should solve the problem.
According to the gmap3 documentation, you still need to call destroy on the map before removing the dom element.
HTML code
<div>
<div id="map"></div>
</div>
restore​
JavaScript
var dlat = 53.9783997; // default map latitude
var dlng = -1.5666347; // default map longitude
var dzoom = 6; // default map zoom
var dmaptype = "roadmap"; // default map type
// create gmap
$('#map').gmap3({
action: 'init',
options: {
center: [dlat, dlng],
zoom: dzoom,
mapTypeId: dmaptype,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
scrollwheel: true,
streetViewControl: true
}
});
function restore() {
$('#map').gmap3({
action: 'destroy'
});
var container = $('#map').parent();
$('#map').remove();
container.append('<div id="map"></div>');
// create new gmap
$('#map').gmap3({
action: 'init',
options: {
center: [dlat, dlng],
zoom: dzoom,
mapTypeId: dmaptype,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
scrollwheel: true,
streetViewControl: true
}
});
}​
Here's an alternative method:
rather than destroying the map and recreating it entirely, you could save the initial state and the restore it to that state like this: http://jsfiddle.net/UvAL3/1/
(these functions existed as part of the API in V2)

Categories

Resources