Javascript function Element makes others JS function not working - javascript

I'm using a script (not made by myself) in order to show markers in Google MAP API with Markerclustering. I've included this script to one of my page and since then, my jQuery code doesn't work anymore.
I've started debugging with console etc, and I've found what causes the issue, it's this function that is on the top of the page of the marker_cluster JS script:
<script type="text/javascript" src="speed_test.js"></script>
<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', speedTest.init);
</script>
<script src="vendors/markerclustererplus/src/markerclusterer.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=speedTest.init">
</script>
function $(element) {
return document.getElementById(element);
}
var speedTest = {};
speedTest.pics = null;
speedTest.map = null;
speedTest.markerClusterer = null;
speedTest.markers = [];
speedTest.infoWindow = null;
speedTest.init = function() {
var latlng = new google.maps.LatLng(39.91, 116.38);
var options = {
// 'zoom': 10,
// 'center': latlng,
// 'mapTypeId': google.maps.MapTypeId.ROADMAP
zoom: 9,
center: new google.maps.LatLng(46.188, 6.12701),
gestureHandling: "greedy",
disableDefaultUI: true,
zoomControl: true,
fullscreenControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
speedTest.map = new google.maps.Map($('map'), options);
speedTest.pics = data.photos;
var useGmm = document.getElementById('usegmm');
google.maps.event.addDomListener(useGmm, 'click', speedTest.change);
var numMarkers = document.getElementById('nummarkers');
google.maps.event.addDomListener(numMarkers, 'change', speedTest.change);
speedTest.infoWindow = new google.maps.InfoWindow();
speedTest.showMarkers();
};
When I comment this portion of code:
function $(element) {
return document.getElementById(element);
}
then my jquery code works back again, but then the Google Map API doesn't show anymore. I think it's because it's a general function... And it must interract with all the function of the page, and that's causing the issue.
You can find this code here.
The file in question here:
If you have any clue how I can fix this issue I'd really appreciate =)
Thank you and have a good day.

$ refers to jQuery and you are changing it by declaring below function
function $(element) {
return document.getElementById(element);
}
Use some other name for function instead of $.Maybe you can use e
function e(element) {
return document.getElementById(element);
}

Related

Clicking a button to load a map layer, a variable (src) is returned as not defined, despite a function defining it?

Hi I have a button on a website that when users click on it, a google map is supposed to load with a layer on it (kml file).
Clicking the button runs three functions.
1. The function to define what src (the url call to the kml file) is. (concatenation is used here)
2. The function to load the KML file
3. The function to initialize the map.
The problem is the map loads but the layer does not. The console log shows the correct url is being created in step 1, but the log also says that src is not defined, I can only assume step 1 is not being read by 2 & 3!!!
Here is the code:
<button class="button1" onclick="myFunctiongr(); loadKmlLayer(); initialize()">R</button>
<script>
function myFunctiongr(){
var gr = [];
gr.push(url.join('')); *This calls a word from another var*
var name = gr[0];
var map;
var src = "https://www.dropbox.com/s/mziks0p2lkq4dqb/"+name+".kml?dl=1";
console.log(src);
}
function loadKmlLayer(src, map) {
var kmlLayer = new google.maps.KmlLayer(src, {
suppressInfoWindows: true,
preserveViewport: false,
map: map
});
}
function initialize() {
var mapCanvas = document.getElementById('map');
var mapOptions = {
center: new google.maps.LatLng(51.50275896, -0.11535645),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(mapCanvas, mapOptions)
loadKmlLayer(src, map);
}
google.maps.event.addDomListener(window,initialize);
</script>
Read this:
http://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/
Then try:
<script>
var src;
function myFunctiongr(){
var gr = [];
gr.push(url.join('')); *This calls a word from another var*
var name = gr[0];
var map;
src = "https://www.dropbox.com/s/mziks0p2lkq4dqb/"+name+".kml?dl=1";
console.log(src);
}
...

Generate google map error

I have the following script which supposed to generate a basic google map:
$(document).ready(function(){
var weatherAPP = {
generateMap: function(){
console.log('called');
var mapHolder = document.getElementById('#map');
var mapOptions = {
center: new google.maps.LatLng(51.5072, 0.1275),
zoom:10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(mapHolder, mapOptions);
}
};
weatherAPP.generateMap();
});
console.log('called') gets called fine.
I have included the following scripts in order:
google maps api
jquery
script
However I am getting the following error:
Uncaught TypeError: Cannot read property 'offsetWidth' of null
Since your element is: <section id="map"></section>
var mapHolder = document.getElementById('#map');
should be
var mapHolder = document.getElementById('map');
You must have confused it with jQuery or CSS in where you declare ids with the prefix #.
In document.getElementById you have to put the elements ID as it is with no prefix at all
I is happening because you have # in getElementById('#map');
If you remove the # it will work :)
http://jsfiddle.net/zbyqoaju/1/
var weatherAPP = {
generateMap: function () {
console.log('called');
var mapHolder = document.getElementById('map');
var mapOptions = {
center: new google.maps.LatLng(51.5072, 0.1275),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(mapHolder, mapOptions);
}
};
weatherAPP.generateMap();

How to bind google maps using HotTowel?

I am trying to show a simple map in HotTowel.
In home.html page I have that:
<section>
<div id="map-canvas" data-bind="map: map"></div>
</section>
In home.js I have that:
define(['services/logger'], function (logger) {
var vm = {
activate: activate,
title: 'Home View',
map: map
};
return vm;
function activate() {
google.maps.event.addDomListener(window, 'load', initialize);
logger.log('Home View Activated', null, 'home', true);
return true;
}
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
});
How to bind model with view to show map?
EDIT**
The below answer was for Durandal 1.2. In durandal 2.0 the viewAttached event was renamed to attached. You can read Durandals documentation about it here.
Durandal has a viewAttached event that is called on your viewmodel once the view has been databound and attached to the dom. That would be a good place to call the google maps api.
define(['services/logger'], function (logger) {
var vm = {
viewAttached: initialize
title: 'Home View',
map: map
};
return vm;
var map;
function initialize(view) {
logger.log('Home View Activated', null, 'home', true);
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
});
EDIT AGAIN to address peoples comments**
As per Jamie Hammond's comment it is a better practice to scope your DOM transversal to the view that's being attached. If the DOM element is apart of the view.
So, inside your viewAttached (in durandal 1.2) or attached (in durandal 2.0) you would:
var map;
var mapOptions = { /*map options*/ };
var vm = {
attached: function (view) {
var mapCanvas = $('#map-canvas', view).get(0);
map = new google.maps.Map(mapCanvas, mapOptions);
}
}
I haven't messed with Durandal 2.0 at all because I've been pretty busy with work and stuff and when I was messing around with Durandal 1.0 it was just for fun but I do love the framework and hope to one day get to play with 2.0. With that said I did have an issue with generating a map in the viewattached in Durandal 1.0. But, I wasn't using Google maps. I was using Leafletjs. My solution to the problem was creating a delay in the viewAttached that would redraw the map after a short delay. This was because Durandal's transitioning in the view was not working well with leaflets ability to draw the map in the dom element as it was flying and fading in.
So, inside the viewAttached I would draw the map like so:
window.setTimeout(drawMap, 10);
Again, this was a very specific problem I had and not a problem with Durandal. This was more of a problem with Leafletjs not rendering the map correctly when the DOM element was still transitioning in.
Evan,
I'm also trying to get this working but no joy.
I have my html as and viewmodel exactly as you have, and I know the viewAttached composition is being called because I'm getting my logger event - but no map!
The only other thing I can think of is where you call your googlemaps from? I'm doing in in my index.html are you doing the same?
Regards
BrettH,
For me, the problem was that the height was 0px. My module that works looks like this:
define(['plugins/router', 'knockout', 'plugins/utility'], function (router, ko, utility) {
var vm = { };
vm.map = undefined;
vm.compositionComplete = function () {
var myLatlng = new google.maps.LatLng(29.4000, 69.1833);
var mapOptions = {
zoom: 6,
center: myLatlng
}
vm.map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var georssLayer = new google.maps.KmlLayer({
url: 'http://www.visualtravelguide.com/Pakistan-Islamabad.kmz'
});
georssLayer.setMap(vm.map);
utility.resizeElementHeight(document.getElementById('map-canvas'), 10);
$(window).resize(function () {
utility.resizeElementHeight(document.getElementById('map-canvas'), 10);
});
};
return vm;
});
My utility module looks like this:
define(['jquery','knockout'], function ($,ko) {
return {
//resizes an element so height goes to bottom of screen, got this from a stack overflow
//usage:
// resizeElementHeight(document.getElementById('projectSelectDiv'));
//$(window).resize(function () {
// resizeElementHeight(document.getElementById('projectSelectDiv'));
//});
//adjustpixels is an optional parameter if you want to leave room at the bottom
resizeElementHeight: function (element,adjustPixels) {
var height = 0;
var adjust = 0;
if (adjustPixels != undefined)
adjust = adjustPixels;
var body = window.document.body;
if (window.innerHeight) {
height = window.innerHeight;
} else if (body.parentElement.clientHeight) {
height = body.parentElement.clientHeight;
} else if (body && body.clientHeight) {
height = body.clientHeight;
}
element.style.height = ((height - element.offsetTop-adjust) + "px");
},
//looks up name by id, returns blank string if not found
//pass in a list and an id (they can be observables)
LookupNameById: function (l, wId) {
var list = ko.utils.unwrapObservable(l);
var id = ko.utils.unwrapObservable(wId);
var name = '';
$.each(list, function (key, value) {
if (value.Id() == id)
name = value.Name();
});
return name;
},
//sets the widths of the columns of headertable to those of basetable
setHeaderTableWidth: function (headertableid,basetableid) {
$("#"+headertableid).width($("#"+basetableid).width());
$("#"+headertableid+" tr th").each(function (i) {
$(this).width($($("#"+basetableid+" tr:first td")[i]).width());
});
$("#" + headertableid + " tr td").each(function (i) {
$(this).width($($("#" + basetableid + " tr:first td")[i]).width());
});
}
};
});
Hope this helps you.
first go to your main.js and add 'async': '../Scripts/async',
require.config({
paths: {
'text': '../Scripts/text',
'durandal': '../Scripts/durandal',
'plugins': '../Scripts/durandal/plugins',
'mapping': '../Scripts/knockout.mapping-latest',
'async': '../Scripts/async',
'transitions': '../Scripts/durandal/transitions'
},
shim: { mapping: { deps: ['knockout'] } }
});
notice that we need to add async.js in the scripts folder so go to Download async.js download the file and save it in hottowel script folder as async.js
the in the main.js add this
// convert Google Maps into an AMD module
define('gmaps', ['async!http://maps.google.com/maps/api/js?v=3&sensor=false'],
function(){
// return the gmaps namespace for brevity
return window.google.maps;
});
in any viewmodel you can now use it like this
define(['plugins/router', 'knockout', 'services/logger', 'durandal/app', 'gmaps'], function (router, ko, logger, app, gmaps) {
i hope this will help:

jquery link toggle with google maps

Im having problems working out how to get this toggle working, by default it hides the map and when you click show map i want the map to slide down and change the link test to hide map which then of course will slide back up but does not seem to be working..... anyone got any ideas?
Also if anyone knows of a solution for the google maps issue im also having please let me know, because the made is hidden when you show / slides down it does not show most of the map (something about resizing i think i remember reading up on)
i have made a jsfiddle here: http://jsfiddle.net/DfVBb/ although does not work there at all for some reason. thanks in advance!
HTML
<div class="slideToggleBox">
<div id="map_div"> </div>
</div>
show map
JS
<script type="text/javascript">
$('#map_div').hide();
$('#slideToggle').click(function() {
$('#map_div').slideToggle('slow', function() {
$('#slideToggle').text('hide map');
}, function(){
$('#slideToggle').text('show map');
});
return false
});
</script>
Maps JS
$(document).ready(function() {
var latlng = new google.maps.LatLng(53.334583, -0.961674);
var options = {
zoom: 15, // This number can be set to define the initial zoom level of the map
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_div'), options);
var image = new google.maps.MarkerImage('/images/map-icon.png',
new google.maps.Size(680, 178),
new google.maps.Point(0,0),
new google.maps.Point(18, 50)
);
var marker1 = new google.maps.Marker({
position: new google.maps.LatLng(53.334583,-0.961674),
map: map,
icon: image
});
});
</script>
I managed to work out a solution for this and also fixing the resize issue
$(function () {
// create a center
var c = new google.maps.LatLng(53.334583, -0.961674);
//create map options object
var mapOptions = {
zoom: 14,
center: c,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
$("#slideToggle").click(function () {
$('#map_canvas').slideToggle(300, function(){
if ($('#slideToggle').text() !== "hide map") $('#slideToggle').text('hide map');
else $('#slideToggle').text('show map');
google.maps.event.trigger(map, "resize"); // resize map
map.setCenter(c); // set the center
}); // slide it down
});
});
I looked at your fiddle, it has to be cleaned. Based on my understanding, you're trying to toggle Google maps on button click.
Mistakes in your Fiddle:
(1) The Google maps is not initialized. The below is used to initialize Google maps.
google.maps.event.addDomListener(window, 'load', initialize);
(2) Your .slideToggle() has to be cleaned up. It has be somehow like
$('#slideToggle').on('click', function () {
$('#map_canvas').slideToggle('slow', function () {
if ($('#slideToggle').text() !== "hide map")
$('#slideToggle').text('hide map');
else
$('#slideToggle').text('show map');
});
return false;
});
I've created a JSFiddle, please go through it and share your thoughts.

Passing parameters to function that creates a google map doesn't work

I'm assuming this is straight forward, just not having any luck with it.
I have the following functions
function init(myPoint) {
var mapDiv = document.getElementById('map-canvas');
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(myPoint, -122.39031314844),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
function start() {
google.maps.event.addDomListener(window, 'load', init(37.2342));
}
If I remove the param and just hardcode myPoint everything works. However in its current state it does not work. Can someone explain to me what I'm doing wrong.
Thanks
Your function is not called on window load; it is called upon code execution. instead of init(37.2342) you should use function(){init(37.2342);} with addDomListener:
google.maps.event.addDomListener(window, 'load', function () { init(37.2342); });

Categories