Execute a script once on page load - javascript

I was messing about with some code but I am struggling a little bit to achieve what I want. In the example here I have a map which displays when there are coordinates in my fields:
http://jsfiddle.net/spadez/xJhmk/9/
// Generic Map Display
function mapDisplay() {
var latval = $('#lat').val(),
lngval = $('#lng').val();
if ($.trim(latval) != '' && $.trim(lngval) != '') {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(latval, lngval),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
scrollwheel: false,
draggable: false
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
$('#map_canvas').removeClass('hidden');
} else {
$('#map_canvas').addClass('hidden');
}
}
What I want to do is have this execute once per page, so that if there are values in the fields when the page loads then the map displays, but if the values get deleted after the page load or changes, the map will not change, since it read the variables at the start of ther page load only.
Can someone show me on my jsfiddle how that might be displayed please?

You are not calling the function mapDisplay();, on document ready call mapDisplay
jQuery(function($){
mapDisplay();
})
Demo: Fiddle

window.onload = function(){
mapDisplay();
}
This runs your code on the onload event

Use:
$(function()
{
mapDisplay();
}
// Generic Map Display
function mapDisplay() {
var latval = $('#lat').val(),
lngval = $('#lng').val();
if ($.trim(latval) != '' && $.trim(lngval) != '') {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(latval, lngval),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
scrollwheel: false,
draggable: false
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
$('#map_canvas').removeClass('hidden');
} else {
$('#map_canvas').addClass('hidden');
}
}
You declare a function, and after page is loaded (the $(function() {} ), it is executed.

Related

Calling multiple google maps with API key call from wordpress template

I have the following code for my website, basically I want to display 2 google maps with different locations:
function lokacije(){
$output=" <div id='map'></div>
<script>
function initMap() {
var lokacija = {lat: 45.3592940, lng: 14.3495750};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
draggable: false,
scrollwheel: false,
center: lokacija
});
var marker = new google.maps.Marker({
position: lokacija,
map: map,
icon:'http://www.omniaprijevodi.hr/wp
content/uploads/2016/06/map_marker.png'
});
}
</script>
<script async defer src='https://maps.googleapis.com/maps/api/js?
key=AIzaSyAglKEMduJgZf1nN42mHkzeNA4jjpI0JA0&callback=initMap'>
</script>
";
return $output;
}
add_shortcode("lokacije","lokacije");
function lokacije2(){
$output=" <div id='map'></div>
<script>
function initMap() {
var lokacija = {lat: 45.813236, lng: 15.996887};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
draggable: false,
scrollwheel: false,
center: lokacija
});
var marker = new google.maps.Marker({
position: lokacija,
map: map,
icon:'http://www.omniaprijevodi.hr/wp-
content/uploads/2016/06/map_marker.png'
});
}
</script>
<script async defer src='https://maps.googleapis.com/maps/api/js?
key=AIzaSyAglKEMduJgZf1nN42mHkzeNA4jjpI0JA0&callback=initMap'>
</script>
";
return $output;
}
add_shortcode("lokacije2","lokacije2");
I call [lokacije] and [lokacije2] from Wordpress template, but I can't get to display them both, in fact none is displayed. Even if I call [lokacije] twice, I get the map to display only the first time - the second time it doesn't appear. Can someone please help me what I'm doing wrong because I'm having a hard time with this one?
Thank you very much in advance!
First, make sure google api script is loaded before you call the api, and you have to load the script only once. Secondly, your JS code redefines initMap(). Thirdly, you use the same element with ID = map for both maps.
Use wp_enqueue_script() to load the scripts: https://developer.wordpress.org/reference/functions/wp_enqueue_script/
and have something like this for the js:
function initMap(element, lat, lng)
{
var map = new google.maps.Map(element, {
zoom: 16,
draggable: false,
scrollwheel: false,
center: {lat:lat, lng:lng};
});
}
and for the php (assuming you have jquery loaded):
function lokacije1()
{
return sprintf('<div map lat="12.34" lng="56.78"></div>');
}

disable draggable on google maps in mobile

I want to disable dragging of maps in tablet and mobile
var myOptions = {
zoom: 5,
scrollwheel: false,
center: new google.maps.LatLng(lat_mycustom, long_mycustom),
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
on pageload this is working fine..
but i want to be disabled for mobile devices.
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
alert(mobile);
map.setOptions({ 'draggable': false });
}
this is not working though..let me know
Use a global variable at the start like
var drgflag=true;
then use your mobile detection code in which dragflag will set to false
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
alert(mobile);
map.setOptions({ 'draggable': false });
}
Then you can initialize your map
var myOptions = {
zoom: 5,
scrollwheel: false,
draggable:drgflag,
center: new google.maps.LatLng(lat_mycustom, long_mycustom),
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
I hope your mobile detection code works..
You can add it directly also
var myOptions = {
zoom: 5,
scrollwheel: false,
center: new google.maps.LatLng(lat_mycustom, long_mycustom),
mapTypeId: google.maps.MapTypeId.ROADMAP,
draggable: false,
}
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
This person [included link] has added a button to enable/disable for mobile only.
It would be nicer if you could 'click' the map rather than a button. Apple's new '3D Touch' would be perfect for this as pressing harder could activate the drag behaviour of the map.
Perhaps you could adjust the style of the map to a lighter or darker shade depending the mode you were in?
https://gist.github.com/danhannigan/36d61b74ea457224b746
$( ".scroll-lock" ).click(function() {
$( this ).toggleClass( "locked" );
if ($(this).hasClass("locked")) {
map.set('draggable', false);
} else {
map.set('draggable', true);
}
});
simply add the following in your myOptions object for your map setting:
var myOptions = {
...
draggable: !("ontouchend" in document),
...
}
This checks if the "ontouchend" event exists, if it does it means its a touch device, so disable dragging. However, things get a bit complicated on laptops with touchscreens.
Another option would be:
var sw = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var isDraggable = sw > 1024 ? true : false;
var mapOptions = {
draggable: isDraggable,
scrollwheel: false
};
You basically check the width of the screen and if it's within the width span of a tablet, then disable dragging.

Function to turn KML layer on/off

This is my first time posting here. I am new in working with Javascript or Google Maps API. I have a map with one KML layer, and I want to create a checkbox that will turn the layer on or off when clicked. I have seen a lot of examples on the web, but nothing seems to work in my application. Here is the code:
(function() {
window.onload = function() {
var options = {
center: new google.maps.LatLng(44.65, 22.64),
zoom: 10,
mapTypeId: google.maps.MapTypeId.TERRAIN,
mapTypeControl: true,
mapTypeControlOptions: {
mapTypeIds: [
google.maps.MapTypeId.HYBRID,
google.maps.MapTypeId.SATELLITE,
google.maps.MapTypeId.TERRAIN
]
},
streetViewControl: false
};
var map = new google.maps.Map(document.getElementById('map'), options);
var kmlUrl = 'http://googledrive.com/host/0B55_4P6vMjhITEU4Ym9iVG8yZUU/trasee.kml';
var kmlOptions = {
suppressInfoWindows: false,
preserveViewport: false,
};
var trasee = new google.maps.KmlLayer(kmlUrl, kmlOptions).setMap(map);
}
})();
I have no idea what function to create to toggle the visibility of the layer, altough I've created a checkbox in the HTML file:
<input type="checkbox" id="straturi" onClick="togglefunction()" />
Could you give me any advice?
Best regards,
Alexandru
The toggle function should be something like
var toggleKml=function(layer) {
if(layer.getMap()===null) {
layer.setMap(map)
} else {
layer.setMap(null)
}
};
And it needs to be defined in the same context as map and trasee, otherwise it won't see those objects. In your case, you would call it with trasee as parameter
toggleKml(trasee);

google maps v3 heatmap not displaying on page load

I have a mapping page which retrieves a json response and creates the relevant array of points to load a heatmap.
All of this is in the required initialize query which is loaded is called in a jquery document.ready.
Here is the strange thing though, all the external data is returning fine and being populated fine, the points array is fine also.
However when I call the setMap(map) method on the heatmap it does not display. But weirdly if I use an on page link to toggle it on or off it will display. Any ideas?? No errors at all in firebug.
var map;
var markers = [];
var markerLatLngArray = [];
function toggleHeatmap() {
heatmap.setMap(heatmap.getMap() ? null : map);
}
function initialize() {
var map_options = {
center: new google.maps.LatLng(53.4902, -7.96),
zoom: 7,
mapTypeId: google.maps.MapTypeId.TERRAIN,
draggableCursor: 'crosshair',
mapTypeControl: true,
scaleControl: true,
streetViewControl: false,
overviewMapControl: false,
overviewMapControlOptions: {
opened: false
}
};
map = new google.maps.Map(document.getElementById('map_canvas'), map_options);
google.maps.event.addListenerOnce(map, 'idle', function(){
document.getElementById('ajax_loading_icon').style.display = "none";
document.getElementById('map_canvas').style.visibility = "visible";
});
jQuery.get("<?php echo $data_url; ?>", {}, function(data) {
jQuery(data).find("marker").each(function() {
var marker = jQuery(this);
var latlng = new google.maps.LatLng(parseFloat(marker.attr("lat")),
parseFloat(marker.attr("long")));
markerLatLngArray.push(latlng);
});
});
pointArray = new google.maps.MVCArray(markerLatLngArray);
heatmap = new google.maps.visualization.HeatmapLayer({
data: pointArray
});
heatmap.setMap(map);
}
It is a timing problem. The map is not initialized until after heatmap.setMap is called.

Check value of fields before running function in jquery

I basically want to have a script on the page which shows a map when it finds two fields on the page named "lng" and "lat" which have a value.
This means that if there are the fields on the page with values, then it will try and display a map, but if not, then it will not.
This is the code I have so far:
http://jsfiddle.net/spadez/xJhmk/3/
function mapDisplay() {
var latval = $('input[id=lat]').val();
var lngval = $('input[id=lng]').val();
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(latval, lngval),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
scrollwheel: false,
draggable: false
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
}
$(function () {
mapDisplay();
});
I am not very good at jquery at the moment but this is what I tried which didn't work:
if (latval !=NULL && lngval != NULL)){
...my code
}
Can someone with a little more knowledge help me understand why this approach doesn't work please?
Try this
if ( !isNaN(latval) && !isNaN(lngval)) {
So basically it checks if the 2 inputs are numbers, and only if true will step into the if condition.
Also
var latval = $('input[id=lat]').val();
var lngval = $('input[id=lng]').val();
can be safely written as
var latval = $('#lat').val(),
lngval = $('#lng').val();
You can hook up the change event for the inputs that will display the maps
Code
function mapDisplay() {
var latval = $('#lat').val(),
lngval = $('#lng').val();
if (!isNaN(parseFloat(latval)) && !isNaN(parseFloat(lngval))) {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(latval, lngval),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
scrollwheel: false,
draggable: false
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
$('#map_canvas').removeClass('hidden');
} else {
$('#map_canvas').addClass('hidden');
}
}
$(function () {
$('input').on('change', mapDisplay).trigger('change');
});
Check Fiddle
You can do this:
var latval = $('#lat').val();
var lngval = $('#lng').val();
if ($.trim(latval) != '' && $.trim(lngval) != '') {
// You code
No need to do this input[id=lat], you can directly call it like $('#lat')
Use $.trim() to remove the whitespace from the beginning and end of a string.
your code is correct : you just have to add a line in you css in order to view the map:
add
display:block; in #map_canvas
like this :
#map_canvas {
display:block;
height: 150px;
width: 300px;
}
moreover you can change its display setting by setting this display property using jquery(depending upon whether variables have values or not.).
by default textbox returns string value. so for empty textbox you can check :
if(latval=='' && lngval==''){alert('blank');}
else{your code;}
the value returned from text box is not a NULL it is just an empty string so you should check whether the value is empty or not
if(latval !="" && lngval !=""){
Your code
}
and if you want to specific for only numbers , try adding
$.isNumeric()
if($.isNumeric(latval) && $.isNumeric(lngval )){
Your code
}
You can access variables like
var lat = jQuery.trim($('#lat').val());
var lng = jQuery.trim($('#lng).val());
And check if the fields were empty
if(lat == '' && lng == '') {
//do code
} else {
//show the map
$("#mapId").show();
}
As you are prob checking latitude/longtitude, I would also check if they are numeric.
function checkValues() {
var valueOK = false;
if($.isNumeric($('#lat').val())) {
if($.isNumeric($('#lng').val())) valueOK = true;
}
return valueOK;
}
$(function () {
if(checkValues) {
mapDisplay();
}
}

Categories