Create Element to insert an API - javascript

I want to create a div using javascript to put my google map into.
It creates a div, but doesnt put the map api into it. Please help.

You need to make sure the Google Maps API script has loaded before running your code. Currently, you are trying to build the map before the browser has downloaded the map API.
The simplest way to fix this is to change your HTML to this:
<script src="https://maps.googleapis.com/maps/api/js?key="Entered key here deleted it for stackoverflow"&callback=initMap">
<script src="javascript.js"></script>
You could also remove the Google Maps script tag and load it dynamically in javascript.js using jQuery’s $.getScript() or with plain JS using https://github.com/filamentgroup/loadJS, running your code as the callback.

initMap is firing when the script loads, but create isn't getting called until you click that p tag. Here's a way to get around that issue, but still wait for the script to load before allowing clicks:
var mapready = false, createcalled = false;
function create()
{
createcalled = true;
if(mapready){
var newDiv = document.createElement("map");
newDiv.id = "map";
newDiv.style.border="solid";
document.body.appendChild(newDiv);
var uluru = {lat: 54.278556, lng: -8.460095};
var map = new google.maps.Map(document.getElementById('map'), {zoom: 16,center: uluru});
var marker = new google.maps.Marker({position: uluru,map: map});
}
}
function initMap()
{
mapready = true;
if(createcalled) create();
}
In this scenario, if the user clicks the p tag before the map is ready, the create function will fire as soon as the map API finishes loading.

Related

Run a javascript function from another function dynamically [duplicate]

This question already has answers here:
How can I check whether Google Maps is fully loaded?
(12 answers)
How do I include a JavaScript file in another JavaScript file?
(70 answers)
Closed 4 years ago.
I want embed google maps dynamically using javascript. But I keep getting the error: Google is not defined. I am calling the map function from another function.
This is what I have tried.
//The below if statement is run by a send function which sends a POST statement and gets MAP as data on success
if (res == 'MAP')
{
$('#map_class').prepend('<div class="col2 column1 first" id="mapy"><div class="sec2map" style="overflow:hidden;height:550px;width:100%;"><div id="map"></div><script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script></div></div>');
init();
}
function init() {
var mapOptions = {
// How zoomed in you want the map to start at (always required)
zoom: 11,
// disable UI
disableDefaultUI: true,
// The latitude and longitude to center the map (always required)
center: new google.maps.LatLng(40.6700, -73.9400), // New York
// How you would like to style the map.
// This is where you would paste any style found on Snazzy Maps.
styles: [{"featureType":"water","elementType":"geometry","stylers":[{"color":"#e9e9e9"},{"lightness":17}]},{"featureType":"landscape","elementType":"geometry","stylers":[{"color":"#f5f5f5"},{"lightness":20}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"color":"#ffffff"},{"lightness":17}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"color":"#ffffff"},{"lightness":29},{"weight":0.2}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#ffffff"},{"lightness":18}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#ffffff"},{"lightness":16}]},{"featureType":"poi","elementType":"geometry","stylers":[{"color":"#f5f5f5"},{"lightness":21}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#dedede"},{"lightness":21}]},{"elementType":"labels.text.stroke","stylers":[{"visibility":"on"},{"color":"#ffffff"},{"lightness":16}]},{"elementType":"labels.text.fill","stylers":[{"saturation":36},{"color":"#333333"},{"lightness":40}]},{"elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"transit","elementType":"geometry","stylers":[{"color":"#f2f2f2"},{"lightness":19}]},{"featureType":"administrative","elementType":"geometry.fill","stylers":[{"color":"#fefefe"},{"lightness":20}]},{"featureType":"administrative","elementType":"geometry.stroke","stylers":[{"color":"#fefefe"},{"lightness":17},{"weight":1.2}]}] };
// Get the HTML DOM element that will contain your map
// We are using a div with id="map" seen below in the <body>
var mapElement = document.getElementById('map');
// Create the Google Map using our element and options defined above
var map = new google.maps.Map(mapElement, mapOptions);
// Let's also add a marker while we're at it
var marker = new google.maps.Marker({
position: new google.maps.LatLng(40.6700, -73.9400),
map: map,
title: 'Snazzy!'
});
}
When I try to call init(); from the console the map appended but when I try to run from another function I get an error;
As far I can understand your issue is that,
before google map library is loaded properly you are calling the init() function.
if you are using jquery
surround your code in
$(function(){
// code here
});
and in js
surround the code in a document.load function

Map in Framework 7

I am trying to load my map in framework 7 but I am unable to do that. The error I am getting is google is undefined.
Below are my codes
JavaScript code
CascadingApp.onPageInit('admin', function(page) {
initialize();
});
function initialize() {
var map = null;
var latlng;
latlng = new google.maps.LatLng(37.4419, -122.1419);
var options = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map"), options);
}
HTML CODE
<div id="map" style="height:400px; width:1200px;"></div>
<script src="https://maps.googleapis.com/maps/api/js?key= AIzaSyAWzZ-1BPmaWKFT0du3cis82mj9Y5ljIgk&callback=initMap" async defer></script>
Does not load map in the page.
Add google api script<script src="https://maps.googleapis.com/maps/api/js?key= AIzaSyAWzZ-1BPmaWKFT0du3cis82mj9Y5ljIgk&callback=initMap" async defer></script> in your index.html file. Currently api is present admin.html template. So when the
admin view is load
CascadingApp.onPageInit('admin', function(page) {initialize();}); at that time google api is not full loaded i.e asynchronous behavior and throw error google not defined. So simply put google api in your index.html page rest is fine.
Hope it helps you !
I added the Google script at the bottom of my index.html but without the callback function.
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
Next, in my app.js script, declare the variable map as global and create the following function to init the map when the page is fully loaded :
$$(window).on('load', function(e) {
initMap();
});
Define the same initMap function inside app.js and remember set a style to map div (width and height at least).
Hope helpful to you ;-)

How to pass a variable value to src in javascript

I´m working a dynamic way to map certain locations, I´m basing my code on an example by Googlemaps, in this example they map locations statically, using an external file (week) where you write the call to the function, an online initialization and mapping functions, like this:
function initialize() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 16,
center: new google.maps.LatLng(19.43,-99.15),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var script = document.createElement('script');
script.src = 'week';
document.getElementsByTagName('head')[0].appendChild(script);
}
function eqfeed_callback(results){
mapping code
}
the content of week, the external file, is:
eqfeed_callback({"type":"FeatureCollection","features":[{feature01, feature02,... feature_n}]});
I´m able to generate dinamically the features content of week (in fact, the whole content, with the very same structure), but now I need to pass it to the initialization function, now that is the value of a global variable instead of an external file´s content, what I´ve made is to rewrite initialize as a parameter dependant function, in order to make it wait for its parameter to be generated, like this:
function initialize(scriptSource){
map = new google.maps.Map(document.getElementById('map_canvas'), { zoom: 16, center: new google.maps.LatLng(19.43,-99.15), mapTypeId:google.maps.MapTypeId.ROADMAP});
var script = document.createElement('script');
script.src = scriptSource;
document.getElementsByTagName('head')[0].appendChild(script);
}
when initialize is called, scriptSource will be the value of a global variable, with its value being exactly the same as the content of the external file (but now generated dinamically) week; I´ve been trying to make it work, but I think there´s a problem with the way I´m passing the src, how do I do this correctly?
It appears you are attempt to load javascript into a script tag.
Rather than setting the src member, instead set the innerHtml.
The src member is actually the url, not the content, of a script tag.
Also, be weary of other places you are setting the src.
script.src = 'week'; will not work as a uri
script.src = 'week.js'; will work as a uri

How to insert a Google map in a webpage using GreaseMonkey?

Nothing I've tried seems to work.
I found these two links and thought they'd be helpful, but that hasn't worked either.
Dynamically load JavaScript with JavaScript
https://developers.google.com/loader/
Here's roughly what my Greasemonkey script looks like currently:
var init_map = function() {
new google.maps.Geocoder().geocode({address:'1125 NW 12th Ave, Portland, OR'},function(result){
alert(result);
});
}
function loadMaps() {
GM_log("loadMaps called");
google.load("maps", "3", {"callback" : init_map, "other_params":"key=foo&sensor=false"});
}
function loadScript(filename,callback){
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.onload = callback;
fileref.setAttribute("src", filename);
if (typeof fileref!="undefined"){
document.getElementsByTagName("head")[0].appendChild(fileref);
}
}
$(document).ready(
function() {
GM_log("document ready");
loadScript('http://www.google.com/jsapi?key=ABQIAAAAfoo',function(){
loadMaps();
});
}
);
I've found that if I don't include
// #require http://www.google.com/jsapi?key=ABQIAAAAfoo
in the Greasemonkey script, I get a google is undefined error. If I do include it, init_map() never gets called. Any suggestions?
var init_map defines a local variable in the GreaseMonkey context.
If you want to run JavaScript in the context of a webpage, I recommend to inject two <script> tags in the web page (another method is to prefix all of your global variables with unsafeWindow.):
Google's map API
Your script.
Example:
// ==UserScript==
// #name Name of script
// #namespace YourNameSpaceHere
// #match http://blabla.com/*
// #version 1.0
// #run-at document-end
// ==/UserScript==
var head = document.head || document.documentElement;
var script = document.createElement('script');
script.src = 'http://www.google.com/jsapi?key=ABQIAAAAfoo';
head.appendChild(script);
var script2 = document.createElement('script');
script2.textContent = '... code here ..';
head.appendChild(script2);
// Clean-up:
script.parentNode.removeChild(script);
script2.parentNode.removeChild(script2);
E4X instead of a plain string
The easiest option to embed a string of JavaScript code in your GreaseMonkey script, without escaping quotes and newlines is to use the E4X format:
script2.textContent = <x><![CDATA[
alert("test");
]]></x>.toString();
I flagged this question as duplicate of how to use the google maps api with greasemonkey to read a table of addresses and trace the route? but the mod "found no evidence to support it".
So i will just copy-paste what i did in my question, since its not a duplicate...
Nah, just kidding :)
Lets start with your last statement:
I've found that if I don't include // #require
http://www.google.com/jsapi?key=ABQIAAAAfoo in the Greasemonkey
script, I get a google is undefined error. If I do include it,
init_map() never gets called. Any suggestions?
Yes.
First, the google maps API should not be loaded as a #require. Instead, do it like this
API_js_callback = "http://maps.google.com/maps/api/js?sensor=false&region=BR&callback=initialize";
var script = document.createElement('script');
script.src = API_js_callback;
var head = document.getElementsByTagName("head")[0];
(head || document.body).appendChild(script);
Second, add google = unsafeWindow.google, otherwise you get the "google is undefined" error.
So, your code should start like this
var init_map = function() {
google = unsafeWindow.google
new google.maps.Geocoder().geocode . . . . . .
About the rest of your code... well, just click on the link above and there you will find how to create a DIV on the fly, add the map to it, append the DIV to the page in a fixed position, etc.
Feel free to copy whatever you want.
Greasemonkey scripts are free anyway :)
I tested the answers here and in many other places and nothing would work. Maybe because the API is now v3 or who knows.
I am going to post the answer that worked for me, which is quite different from the others I found, and I believe can be used for many other cases. It's arguably a bit ugly, but after all this is script injection and nobody likes injections.
I don't copy the whole thing in jsbin / codepen / etc. because they simply cannot replicate the GS (Greasemonkey) environment (at least yet) and inner workings.
LOADING API
I had control over the destination webpage so this was there instead of being added via GS.
<script src="https://maps.googleapis.com/maps/api/js?key=my-personal-key"></script>
On my experience, if you don't add the key, after a few requests it will fail and you will have to wait some time until it works again.
I also have there a div whith a floating window where I would create my map.
<div style="overflow:hidden; height:500px; width:700px; position:fixed; top:20px; right:20px; border:3px solid #73AD21;">
<div id="gmap_canvas" style="height:500px;width:700px;"></div>
<style>#gmap_canvas img{max-width:none!important;background:none!important}</style>
<div id="Content_Title"></div>
</div>
GS SCRIPT
// Pass whatever data you need to the window
unsafeWindow.mapdata=JSON.stringify(mapdata);
// Define content of script
var script2 = document.createElement('script');
script2.textContent = `
// Get data
mapdata=JSON.parse(window.mapdata);
// Create map and use data
function initializeX2() {
// some stuff ...
// Create map
var mapCanvas = document.getElementById('gmap_canvas');
var myLatLng = {lat: parseFloat(mapdata[max].latitude), lng: parseFloat(mapdata[max].longitude)};
var mapOptions = {
center: myLatLng,
zoom: 15,
mapTypeControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(mapCanvas, mapOptions);
var marker=[];
var contentInfoWindow=[];
var infowindow=[];
// Create markers
for (var i = max ; i > max-iterations ; i--) {
// Create marker
var BLatLng={lat: parseFloat(mapdata[i].latitude), lng: parseFloat(mapdata[i].longitude)};
console.log(BLatLng);
marker[i] = new google.maps.Marker({
position: BLatLng,
map: map
});
// Create infowindow
contentInfoWindow[i]=mapdata[i].number + " - " + mapdata[i].name;
infowindow[i] = new google.maps.InfoWindow({content: contentInfoWindow[i] });
// The function has this strange form to take values of references instead of references (pointers)
google.maps.event.addListener(marker[i], 'click', function(innerKey) {
return function() {
infowindow[innerKey].open(map, marker[innerKey]);
}
}(i));
// Open markers
infowindow[i].open(map, marker[i]);
}; // end of for
}; // end of initializeX2
initializeX2();
`; // End of string to be added to page
// Add script to the page
var head = document.head || document.documentElement;
head.appendChild(script2);
// Clean-up:
script2.parentNode.removeChild(script2);
Some explanations
In my case the markers are opened when created, and multiple may stay open. That is my desired behaviour. If you want something else you have to search around.
This may help you.
Create only ONE window to have only one infowindow open at a time ( http://www.aspsnippets.com/Articles/Google-Maps-API-V3-Open-Show-only-one-InfoWindow-at-a-time-and-close-other-InfoWindow.aspx )
If someone has got the other solutions working with API v3 (via google = unsafeWindow.google ) I would be very interested to know.

Google map error: a is null

I have a program that I want to use google maps for. The problem is I get an error that says a is null where a is a var used in the google map api. Here is how I call my google map:
//Creates a new center location for the google map
var latlng = new google.maps.LatLng(centerLatitude, centerLongitude);
//The options for the google map
var myOptions = {
zoom: 7,
maxZoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//Creates the new map
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
And here is what my HTML tag looks like:
<div id = "map_canvas"></div>
I get the lat and lng on page load through the url. These values are passed in correctly so I know that is not the problem. I think that it has to do with the var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); not being correct. Any suggestions?
EDIT: Here is the error message:
a is null
fromLatLngToPoint(a=null)
yg(a=null, b=Object { zoom=7, maxZoom=12, more...})
d(d=Document Default.aspx?lat=30.346317&lng=105.46313, f=[function()])
d(a=undefined)
d()
[Break On This Error] function Qf(a){a=a.f[9];return a!=i?a:...);function sg(a){a[ic]&&a[ic]Vb}
Make sure you specify the size of the element that holds the map. For example:
<div id="map_canvas" style="width: 500px; height: 500px;"></div>
Also make sure your map variable is defined in the global scope and that
you initialize the map once the DOM is loaded.
You are probably not listening for the onload event that fires when the page is completely loaded. As a result, your script is running but the div you are creating doesn't yet exist. Use jQuery to listen for this event, like so:
$(document).ready(function () {
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
});
If you don't want to use jQuery, then add an event listener to body.onload
This rather cryptic error means that the script can't find the map div.
This could happen for a couple of reasons.
1. You're using the wrong ID to refer to the map.
Check your ids (or classes) and make sure the element you're referring to actually exists.
2. You're executing the script before the DOM is ready.
Here's a jQuery example. Notice we're triggering initialise on document ready, not onDOMReady. I've taken the liberty of wrapping the script in a closure.
(function($) {
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
}
$(document).ready(initialize);
})(jQuery)
You could also use:
google.maps.event.addDomListener(window, 'load', initialize);
if you prefer a Google solution.
Had the exact same problem and this is have i fixed it for me.
The thing was that I had 2 google maps in my website - one in the footer and the other one on the contact page, but i called them both in one JS file like so:
var map1 = new google.maps.Map(document.getElementById("map-canvas-footer"), settings1);
var map2 = new google.maps.Map(document.getElementById("map-canvas"), settings2);
But the thing is that the object with id="map-canvas" was located only on the contact page.
So at first you have to check if that element exists on the page like so:
if ($("#map-canvas-footer").length > 0){
var map1 = new google.maps.Map(document.getElementById("map-canvas-footer"), settings1);
}
if ($("#map-canvas").length > 0){
var map2 = new google.maps.Map(document.getElementById("map-canvas"), settings2);
}
I hope this can help someone else as well ;)
This happens when the map is not yet loaded. You should build your map when the Maps API JavaScript has loaded. Executing the function to initialize your map only when the API has fully loaded passing it to the "callback" parameter in the Maps API bootstrap.
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 = "http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=TRUE_OR_FALSE&callback=initialize";
document.body.appendChild(script);
}
window.onload = loadScript;
This is actually in the Maps API Docs here. Hope this helps!
Make sure that your canvas div (Div associated with the map) exists.
Sometimes, if we rename the div's id attribute.
Then it creates problem as it does not get the canvas div.
I got this error once. Make sure the map script runs only on pages using the map. You can check if the map exists by using an "if". Something like this:
if ($('mapClass').length>0) { // here you run the google maps functions }
See ya
Solved, the google map type a error, make sure you get object var map = document.getElementById('map-canvas') returning properly using alert(map). Check the div container id name same as specified in getElementByid.
I have also stuck with the same type a error, fixed it by checking getElementByid('map-canvas'). Sample code enter link description here
I have fixed it removing my "style" property from the "div" tag an declaring it correctly, in a css file
My response is bit old but for those who still come here for reference, I have a similar solution. I put map initialization code as specified here https://developers.google.com/maps/documentation/javascript/adding-a-google-map
inside jQuery document ready function. Below is the code that worked in my case:
$(document).ready(function () {
var uluru = {lat: -25.344, lng: 131.036};
var map = new google.maps.Map( document.getElementById('embedmap'), {zoom: 14, center: uluru} );
var marker = new google.maps.Marker({position: uluru, map: map});
});

Categories