Google Maps JS API 3 Uncaught Security Error - javascript

I'm receiving the following error in the console when loading Google Maps asynchronously in a Rails App using Turbolinks (not sure if turobolinks is related to the error). The map loads as expected, but I can't seem to clear this error.
Uncaught SecurityError: Blocked a frame with origin
"https://www.google.com" from accessing a frame with origin
"https://example.com". Protocols, domains, and ports must match.
The initialization script is very similar to the vanilla example in the API docs, except that the loadScript function is triggered on the turbolinks page:load event.
function initialize() {
var lat = $('#map-canvas').data('lat');
var long = $('#map-canvas').data('long');
var mapOptions = {
zoom: 14,
center: new google.maps.LatLng(lat, long),
mapTypeId: google.maps.MapTypeId.SATELLITE,
disableDefaultUI: true,
zoomControl: true
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
function loadScript() {
if ( $( "#map-canvas" ).length ) { //only initialize on map pages
if (typeof google == "undefined") { //prevent duplicate loading
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp' +
'&signed_in=true&callback=initialize';
document.body.appendChild(script);
}else{
initialize();
}
}
}
$(document).on("ready page:load", loadScript);

Related

Google Maps are not showing with domainname.com

JavaScript:
<script async defer src="https://maps.googleapis.com/maps/api/js?key=mykey"type="text/javascript"></script>
JavaScript Function:
<script type="text/javascript">
var geocoder;
var map;
var latlng;
function codeAddress(address) {
geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latlng=results[0].geometry.location;
latlng = new google.maps.LatLng(latlng);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
map.setCenter(results[0].geometry.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);
}
});
}
}
</script>
I reads following questions but my problem is not solved.
Google Maps JavaScript API RefererNotAllowedMapError
Google maps API referrer not allowed
Google Maps API error: Google Maps API error: RefererNotAllowedMapError
The problem is , when i open my website like this.
http://mysiste.com/contactus
it is not showing map and showing following error.
Google Maps API error: RefererNotAllowedMapError https://developers.google.com/maps/documentation/javascript/error-messages#referer-not-allowed-map-error
Your site URL to be authorized: http://comprettainsurance.com/contactus"
while if i open my site like this.
http://www.mysiste.com/contactus
the maps are working perfectly.
My Credential Page where i add domain like this.
so why it is not showing maps without www?
*.comprettainsurance.com/* does not match http://comprettainsurance.com/contactus (it matches any subdomain of comprettainsurance.com, but not the domain itself).
You need to add an additional referrer line:
comprettainsurance.com/*
Use simple like this this worked for me everywhere
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=key&libraries=places,drawing,geometry"></script>
when you use defer the script will be loaded when the document is closed- the content has been loaded. Furthermore external deffered scripts will be parsed after inline defferred scripts.

How does the Google Maps API work with AngularJS?

How is it possible to use the Google Maps API with AngularJS?
I am using this code in my AngularJS app:
<style>
#googleMap {
width: 200px;
height: 200px;
}
</style>
<div id="googleMap"></div>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js"></script>
<script language="javascript">
var map;
function initialize() {
var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
This code is in the view and not in the controller.
I have other functions in the view and they work, but google map is still not working.
This is the error I get in the browser console:
Error: google is not defined
#http://localhost:3000/js/jquery-1.11.2.min.js line 2 > eval:10:2
.globalEval/<#http://localhost:3000/js/jquery-1.11.2.min.js:2:2615
.globalEval#http://localhost:3000/js/jquery-1.11.2.min.js:2:2589
.domManip#http://localhost:3000/js/jquery-1.11.2.min.js:3:23105
.after#http://localhost:3000/js/jquery-1.11.2.min.js:3:21067
Cehttp://localhost:3000/js/angular/lib/angular.min.js:176:70
n#http://localhost:3000/js/angular/lib/angular-route-segment.min.js:7:5868
.compile/http://localhost:3000/js/angular/lib/angular-route-segment.min.js:7:6428
Pe/this.$gethttp://localhost:3000/js/angular/lib/angular.min.js:128:120
p#http://localhost:3000/js/angular/lib/angular-route-segment.min.js:7:2649
this.$gethttp://localhost:3000/js/angular/lib/angular-route-segment.min.js:7:3989
f/<#http://localhost:3000/js/angular/lib/angular.min.js:112:20
Pe/this.$gethttp://localhost:3000/js/angular/lib/angular.min.js:125:301
Pe/this.$gethttp://localhost:3000/js/angular/lib/angular.min.js:122:390
Pe/this.$gethttp://localhost:3000/js/angular/lib/angular.min.js:126:56
l#http://localhost:3000/js/angular/lib/angular.min.js:81:169
S#http://localhost:3000/js/angular/lib/angular.min.js:85:301
vf/http://localhost:3000/js/angular/lib/angular.min.js:86:315
What am I doing wrong?
I searched the web but everyone seems to be using libraries like angular-google-map or ui-map. Why is no one using the direct API?
You can implement google maps in angularjs without using any plugins like this,
<!--use this div where ever you want to create a map-->
<div id="map"></div>
define the width and height for map div,
#map {
height:420px;
width:600px;
}
in controller you glue this id="map" with scope like this,
$scope.mapOptions = {
zoom: 4,
center: new google.maps.LatLng(41.923, 12.513),
mapTypeId: google.maps.MapTypeId.TERRAIN
}
$scope.map = new google.maps.Map(document.getElementById('map'), $scope.mapOptions);
if you want to create markers for the cities or countries you want,
var cities = "Atlanta, USA";
var geocoder= new google.maps.Geocoder();
$scope.markers = [];
var createMarker = function (info){
var marker = new google.maps.Marker({
map: $scope.map,
position: new google.maps.LatLng(info.lat(), info.lng())
});
}
geocoder.geocode( { 'address': cities }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
newAddress = results[0].geometry.location;
$scope.map.setCenter(newAddress);
createMarker(newAddress)
}
});
Last but not least make sure you added the google maps api script before doing all this stuff,
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"> </script>
Here is the working plunker with this code, inside a bootstrap model,
http://embed.plnkr.co/VT7cO0L2ckSWG6g63TVG/preview
Reference
Hope this helps!
It was late to post but I have done this as solution. By this there is no need to add the google map script src in the head of the html or there is no chance of any error for google map src related errors. The script will be added automatically by the loadScript function. In angular it is needed to add new js src in partials rather than the head of main script. So I think this will be the best solution
I used this code chunk into my controller.
$scope.initialize = function() {
$scope.mapOptions = {
zoom: 8,
center: new google.maps.LatLng(22.649907498685803, 88.36255413913727)
};
$scope.map = new google.maps.Map(document.getElementById('googleMap'), $scope.mapOptions);
}
$scope.loadScript = function() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.google.com/maps/api/js?sensor=false&callback=initialize';
document.body.appendChild(script);
setTimeout(function() {
$scope.initialize();
}, 500);
}
setTimeout is there because some time is needed for google map src to be downloaded and be ready. & callback=initialize is needed because by this google map will be ready for a callback.The main problem was that the code google.maps.event.addDomListener(window, 'load', initialize) was not executing if I add the google map src in partial rather than the head of main index.html. But this setup works flawlessly.
And this chunk to the html
<div class="form-group col-lg-12" id="googleMap">
<center>Waiting for the map...</center>
</div>
Now place ng-init="loadScript()" anywhere in any outer div so that loadScript initializes before.

dynamic content loading via ajax does not load gmap

I am dynamically loading content into a page and one of the pages has a google map point. Everything works fine except map point doesn't show up. Map api is loaded asynchronously so if I understand it correct it should work.
Example taken from official google's documentation
<script>
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&' +
'callback=initialize';
document.body.appendChild(script);
}
</script>
<div class="joomsport-event-location">
<div class="map" id="map-canvas" style="height: 50%"></div>
<script>
loadScript();
alert('loading'); // test if it's called
</script>
</div>
This is source that is loaded into another page using jQuery. And once loaded I get expected alert. Am I missing something ? Or it's not even possible what I am trying to do?

Geolocation Uncaught TypeError: Cannot read property 'coords' of undefined

I'm messing with the Google Maps API with Geolocation. Everything is working as expected, however I keep getting this error in my console:
Uncaught TypeError: Cannot read property 'coords' of undefined
Here is my Geo Check:
// Does this browser support geolocation?
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(initialize, locationError);
} else {
showError("Your browser does not support Geolocation!");
}
My Success Handler:
function initialize(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var acc = position.coords.accuracy;
// Debugging
console.log(position.coords);
console.log("Accuracy: "+acc+"\nLatitude: "+lat+"\nLongitude: "+lon);
// Google Maps API
var myLatlng = new google.maps.LatLng(lat,lon);
var mapOptions = {
center: new google.maps.LatLng(lat, lon),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"Hello World!"
});
}
I then initialize the map in my body tag <body id="map" onload="initialize()">
The map renders fine, everything is working as expected. When I log position.coords to my console, I get a clean readout. Why do I keep receiving this error?
Google and SO searches rendered no results...
Cheers
When document is loaded, the initialize method is called with no argument.
That's why you get the error.
Try this way instead:
function initCoords() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(initialize, locationError);
} else {
showError("Your browser does not support Geolocation!");
}
}
and in your html code:
<body id="map" onload="initCoords()">
Keep the initialize function as is.
The error is probably here
<body id="map" onload="initialize()">
You're calling the initialize function with no parameters. Therefore the 'position' parameter is undefined
function initialize(position) {
var lat = position.coords.latitude;
Its as if you called
var lat = undefined.coords.latitude
If you are getting the error on google maps in cordova/phonegap on initialization before using the map object, make sure the google map html data-lat and data-long properties exist.
Here is a sample,
<div class="widget uib_w_20 maps-size d-margins"
data-uib="media/google_maps" data-ver="0" data-rpath="null"
data-zoom="8" id="google-maps" data-center-auto="true"
data-lat="41.309697" data-long="-72.9370447">
without data-lat and data-long, and testing as web app, will fail during google map initialization

"a is null" even after Google map is successfully loaded

I have a set of jQuery UI tabs that each load project.php using ajax. Depending on the parameters passed to the script, a different Google map is displayed using the following JavaScript inside project.php:
var tab_index = $('#tabs').tabs('option', 'selected');
$('.site_map:visible').css('height','300px');
MapID = $('.site_map:visible').attr('id');
if (MapID !== 'map-new'){
var map_id = 'map-'+tab_index;
$('.site_map:visible').attr('id', map_id);
} else {
MapNewSite();
}
var latlng = new google.maps.LatLng(19,-70.4);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
arrMaps[tab_index] = new google.maps.Map(document.getElementById("map-" + tab_index), myOptions);
arrInfoWindows[tab_index] = new google.maps.InfoWindow();
placeMarker($('.site_details:visible .inpLat').val(), $('.site_details:visible .inpLng').val(), tab_index);
function MapNewSite(){
arrMaps[tab_index] = new google.maps.Map(document.getElementById("map-new"), myOptions);
placeMarker(19,-70.4,tab_index);
arrInfoWindows[tab_index] = new google.maps.InfoWindow();
}
Each map loaded using parameters returned by a query of my database loads without any problems. However, in one last instance, I load project.php in a tab without any parameters so as to have a blank tab for users to manipulate. The signal that the map is not to be loaded using database coordinates is that the id of its div is "map-new".
The map generated in this tab loads, but then gives me the "a is null" error which usually means it couldn't find a div with the id specified to initialize the map. What is causing this error even after the map has loaded? How do I stop the error from occurring?
Here is the JavaScript in the parent page containing the tab site:
var arrMaps = {};
var arrInfoWindows = {};
var arrMarkers = {};
function placeMarker(lat, lng, tab_index){
map = arrMaps[tab_index];
var bounds = new google.maps.LatLngBounds();
var latlng = new google.maps.LatLng(
parseFloat(lat),
parseFloat(lng)
);
bounds.extend(latlng);
createMarker(latlng, tab_index);
map.fitBounds(bounds);
zoomChangeBoundsListener =
google.maps.event.addListener(map, 'bounds_changed', function(event) {
if (this.getZoom()){
this.setZoom(10);
}
google.maps.event.removeListener(zoomChangeBoundsListener);
});
}
function createMarker(latlng, tab_index) {
var html = 'Click here to move marker';
arrMarkers[tab_index] = new google.maps.Marker({
map: arrMaps[tab_index],
position: latlng
});
arrInfoWindows[tab_index] = new google.maps.InfoWindow();
google.maps.event.addListener(arrMarkers[tab_index], 'click', function() {
arrInfoWindows[tab_index].setContent(html);
arrInfoWindows[tab_index].open(arrMaps[tab_index], arrMarkers[tab_index]);
});
}
$(function() {
$( "#tabs" ).tabs({
ajaxOptions: {
error: function( xhr, status, index, anchor ) {
$( anchor.hash ).html(
"Couldn't load this tab. We'll try to fix this as soon as possible. " +
"If this wouldn't be a demo." );
}
},
cache: true
});
});
Take a look to http://www.pittss.lv/jquery/gomap/. Easy to use and very powerful. I myself use it.
It turns out I was accidentally initializing the map both inside the if and outside of it.

Categories