Reloading google map - javascript

i have 3 different google maps on my site, one for when viewing on desktop, tablet and mobile, when i resize my browser which people might do the new map pointer that has now resized isn't in the right place until i refresh the page, i want to just reload the iframe, im very new to javascript and tried this but its nots working
<script type="text/javascript">
if( $(window).width() == 985){
document.getElementById('map-desk').contentWindow.location.reload(true);
}
if( $(window).width() == 975){
document.getElementById('map-tab').contentWindow.location.reload(true);
}
if( $(window).width() == 765){
document.getElementById('map-mob').contentWindow.location.reload(true);
}
</script>
so like when the screen equals a certain width the iframe with that id reloads or refreshes

There's no actual event handler so it'll only fire once, when the browser loads (which is obviously not what you want). As you're using jQuery, wrap your code in:
$(window).resize(function() {
// code goes here...
});
... which will run the code inside every single time there's even a minute change to the browser size. Though you're going to come across the issue that $(window).width() is very rarely going to hit that exact pixel value. I'm not certain of the best solution, but something involving checking the condition +/- 30 pixels either way or so might work.

I think you are looking for the following event in jQuery
window.onresize = function(event) {
//your code to resize and reload here
}

Google maps reloads itself if the mapdiv is resized. Give 100% width to mapdiv. It will fit the size of the window. If you want to change the contents of maps (layers, markers, routes...), you should use google map events. Events, options and methods are listed here:https://developers.google.com/maps/documentation/javascript/reference

Related

detect a change of screen resolution, and execute a code or another in javascript

I have this doubt, I have a menu in which I run a javascript code or another depending on whether its width is greater or less than its height, works me well the first time the screen resolution is detected, but if there is a change of resolution or a change of orientation does not detect it, and despite for example of having changed to portrait orientation still executing the landscape orientation code. Is there any way to solve this? regards
You could use an eventlistener and listen on the resize event.
window.addEventListener('resize', () => {
// function body
});
But I think this is rather a styling issue and you should consider to use a different approach.
Here is an extention of #mstruebing 's answer :
function resisePageMobile(){
if (window.innerWidth <= 696) { //Detect mobile
aside.classList.remove('pc-stuff');
aside.classList.add('mobile-stuff');
}else{ //Detect other higher resolution screens
aside.classList.remove('mobile-stuff');
aside.classList.add('pc-stuff');
}
}
resisePageMobile();//run once on page load
//then attach to the event listener
window.addEventListener('resize',resisePageMobile);
Running this function once at the start of the page is important because the resize event will not trigger until the window is getting resized so we must initialize page at the start !

JQuery - Test window has been resizes over a threshold

hope you can help
My current project requires me to recall a set of functions on window resize so that I can keep the responsive nature correct. However the code I am using is rather twitchy as it calls the functions even if the window is resized by 1px.
I am relatively new to jQuery but learning more and more every day, but this is something I'm struggling to find a way to do.
In an ideal world I would like to call the functions when the window has been resized over a breaking point at anytime, for example:
say the breaking point is 500px, the initial load size is 400px the user resizes to 600px, so over the threshold so call the functions again.
It would also need to work in reverse... so window (or load) size 600px, breaking point 500px, resize to 400px call functions.
Here's the code I'm currently:
var windowWidth = $(window).width();
var resizing = !1;
$(window).resize(function(a) {
!1 !== resizing && clearTimeout(resizing);
resizing = setTimeout(doResize, 200);
});
function doResize() {
call_these_functions();
}
Cheers for the help guys
Thanks for the reply Zze
I am using something similar to what you've put, but I have it based within the start of my functions to filter what each thing does based on the window size. My problem is that these are getting called far too often and causing issues / twitchy behaviour.
For example I'm having issues on a tablet I'm testing on, when you scroll down, the scrollbar that appears on the right seems to trigger the window resize... causing functions to be called again that automatically accordion up or .hide() elements to their initial loaded state.
So my thinking is if I can test it's actually broken a set threshold rather than just what size the window is then it will be far more reliable.
There are some really handy jQuery functions available and it looks like you are very close to cracking this yourself. Hope this helps though.
$(window).resize(ResizeCode); // called on window resize
$(document).ready(function(e) { ResizeCode(); }); // called once document is ready to resize content immediatly
function ResizeCode()
{
if ($(window).width() < 500){
//insertCode
}
else if($(window).width() >= 500){
//insertCode
}
}
Update
If we are looking to 'restrict' the call time of this function, then you could add an interval which updates a bool every time it ticks, and then check this bool in the previous code:
var ready = true;
setInterval(function(){ready = true;}, 3000);
function ResizeCode()
{
if (ready)
{
// run code
ready = false;
}
}
But i would suggest storing the width and height of the window in a var and then comparing the current window with the var when the window is resized, that way you can tell if the window has actually been resized over 'x' amount or if it is that weird bug you've found.
Looks like i've found a solution that's going to do what i need with a little work (fingers crossed as i'm currently working on it), from http://xoxco.com/projects/code/breakpoints/
Thanks for the help Zze

Why aren't my elements correctly sized when the page loads?

I'm trying to get a navigation to hide if there isn't enough room in the window. The navigation is contained in a wrapper that also contains a logo, and so to calculate if there is enough room I use the following:
if ($(window).width() < ($('#logo').outerWidth() + $('#nav').outerWidth()))
$('#nav').hide();
I have that run when the document is ready and when the window is resized. What I noticed was if the window started off too small it wasn't hiding the nav so I looked into it further. What I found is the nav width that is being calculated when the document is ready is incorrect.
The nav consists of and they are all calculated to be about 3-4px too small, but when resizing the window the values get correctly calculated. Does anyone know why this might be?
It could be that some images haven't fully loaded when the function is called. Try binding the event to;
$(window).load();
instead of;
$(document).ready();
This will make the function run after the page has completely finished loading, including images whereas $(document).ready() only waits for the DOM to load.
$(window).load(function () {
if ($(window).width() < ($('#logo').outerWidth() + $('#nav').outerWidth()))
$('#nav').hide();
});
As Terry pointed out, on a very resource heavy site this would result in a large delay before hiding the nav bar which could be a problem, so you could instead check the status of the #nav or #logo element's load.
$('#nav').load(function () {
if ($(window).width() < ($('#logo').outerWidth() + $('#nav').outerWidth()))
$('#nav').hide();
});
The problem typically comes from the fact that the browser is still computing the size of the elements when you call your line of code.
Try to keep an eye on what sizes you are changing in your $(document).ready() function (would have been good to paste the whole code here...). Any change to the size of an element could affect all others.

Force mobile browser zoom out with Javascript

In my web app, I have some thumbnails that open a lightbox when clicked. On mobile, the thumbnails are small and the user typically zooms in. The problem is that when they click to play it, the lightbox is outside of the viewable area (they have to scroll to the lightbox to see the video). Is it possible to force a mobile browser to zoom out so they can see the whole page?
Making the page more responsive is not an option right now; it is a fairly large web application and it would take a huge amount of time to refactor.
Dug through a lot of other questions trying to get something to zoom out to fit the entire page. This question was the most relevant to my needs, but had no answers. I found this similar question which had a solution, although implemented differently, and not what I needed.
I came up with this, which seems to work in Android at least.
initial-scale=0.1: Zooms out really far. Should reveal your whole website (and then some)
width=1200: Overwrites initial-scale, sets the device width to 1200.
You'll want to change 1200 to be the width of your site. If your site is responsive then you can probably just use initial-scale=1. But if your site is responsive, you probably don't need this in the first place.
function zoomOutMobile() {
var viewport = document.querySelector('meta[name="viewport"]');
if ( viewport ) {
viewport.content = "initial-scale=0.1";
viewport.content = "width=1200";
}
}
zoomOutMobile();
Similar to Radley Sustaire's solution I managed to force unzoom whenever the device is turned in React with
zoomOutMobile = () => {
const viewport = document.querySelector('meta[name="viewport"]');
if ( viewport ) {
viewport.content = 'initial-scale=1';
viewport.content = 'width=device-width';
}
}
and inside my render
this.zoomOutMobile();
1 edge case I found was this did not work on the Firefox mobile browser
I ran in a similar problem, rather the opposite, I guess, but the solution is most certainly the same. In my case, I have a thumbnail that people click, that opens a "popup" where users are likely to zoom in to see better and once done I want to return to the normal page with a scale of 1.0.
To do that I looked around quite a bit until I understood what happens and could then write the correct code.
The viewport definition in the meta data is a live value. When changed, the system takes the new value in consideration and fixes the rendering accordingly. However, the "when changed" is detected by the GUI and while the JavaScript code is running, the GUI thread is mostly blocked...
With that in mind, it meant that doing something like this would fail:
viewport = jQuery("meta[name='viewport']");
original = viewport.attr("content");
force_scale = original + ", maximum-scale=1";
viewport.attr("content", force_scale); // IGNORED!
viewport.attr("content", original);
So, since the only way I found to fix the scale is to force it by making a change that I do not want to keep, I have to reset back to the original. But the intermediary changes are not viewed and act upon (great optimization!) so how do we resolve that issue? I used the setTimeout() function:
viewport = jQuery("meta[name='viewport']");
original = viewport.attr("content");
force_scale = original + ", maximum-scale=1";
viewport.attr("content", force_scale);
setTimeout(function()
{
viewport.attr("content", original);
}, 100);
Here I sleep 100ms before resetting the viewport back to what I consider normal. That way the viewport takes the maximum-scale=1 parameter in account, then it times out and removes that parameter. The scale was changed back to 1 in the process and restoring my original (which does not have a maximum-scale parameter) works as expected (i.e. I can scale the interface again.)
WARNING 1: If you have a maximum-scale parameter in your original, you probably want to replace it instead of just appending another value at the end like in my sample code. (i.e. force_scale = original.replace(/maximum-scale=[^,]+/, "maximum-scale=1") would do the replace--but that works only if there is already a maximum-scale, so you may first need to check to allow for either case.)
WARNING 2: I tried with 0ms instead of 100ms and it fails. This may differ from browser to browser, but the Mozilla family runs the immediately timed out timer code back to back, meaning that the GUI process would never get a chance to reset the scale back to 1 before executing the function to reset the viewport. Also I do know of a way to know that the current viewport values were worked on by the GUI... (i.e. this is a hack, unfortunately.)
This one works for me
let sw = window.innerWidth;
let bw = $('body').width();
let ratio = sw / bw - 0.01;
$('html').css('zoom', ratio);
$('html').css('overflow-x', 'hidden');
Its fits html to screen and prevents from scrolling. But this is not a good idea and work not everywhere.
var zoomreset = function() {
var viewport = document.querySelector("meta[name='viewport']");
viewport.content = "width=650, maximum-scale=0.635";
setTimeout(function() {
viewport.content = "width=650, maximum-scale=1";
}, 350);
}
setTimeout(zoomreset, 150);
replace 650 with the width of your page

Google Maps not rendering completely on page?

I have a google maps on my page with a search pane I built myself which can be displayed and hidden at will. It covers like lets say 200 pixels of the map on a side. The thing is that when I resize my map or so the area where the pane overlaps is unrendered i.e the map doesn't render there for some reason.
Check out this link
In the Box type in lets say OMDB which is an icao code for an airport and press enter.
The results are shown and you see the pane. Now click on the full screen link and then click on the airports tab to make the panel go away - you see now that part of the map hasn't rendered at all...I have to drag the map around and that only partially renders that area. How can I fix it?
FYI I've run it on Google Chrome, Firefox and IE8 on Windows XP. Is there a way to like force complete rendering of a map or so? This is quite an erratic problem and could it be concerne with my code or is it a host issue? Or does Google just don't like me? :(
EDIT: See the big ugly patch on the side. Its unrendered area where the map should have been rendered as well. No amount of zooming in and panning is helping clear this :(
I'm not able to reproduce the issue you are having, but it looks similar to another issue I've seen with google maps.
It looks like you might be running afoul of the way google maps determines which tiles are in view. It calculates this only once, when the map is loaded into the div the first time, and if the div grows, then not enough map will be drawn. Fortunately, this is easy to deal with. any time the container may have resized, use the checkResize() method on the map instance, and the clipping area will be recomputed from the container's current size.
Yes, you MUST supply a real pixel height and width of the container DIV. This is in fact detailed in the Google API.
By using something like this:
<div id="map_canvas" style="width:500px;height:500px;"></div>
instead of
<div id="map_canvas"></div>
you'll be home free !
As far as I can see it works fine on OS X 10.6.2 in Google Chrome.
http://i33.tinypic.com/sfe3ah.png
Only problem is that Copenhagen Airport is nowhere near the location your application implies. And LAX is in the middle of the ocean ;-)
Edit:
I see your screenshot, and it would appear to me that somehow Google Maps does not render the part of the map that was covered by the search and search results pane, and afterwards the rendering is not triggered correctly upon hiding the search pane.
I haven't been able to find a decent render triggerer in the Google Maps API, but I think you should try something like programatically zooming in and out or moving the center of the map somewhere else and back, in order to maybe force the re-rendering of the map.
Alternatively you could try manually triggering some of the events that you think might set off a rerendering of the map, for example google.maps.event.trigger(map, 'resize').
I know these suggestions feel like a terrible hacking way of making it work, and I am highly unsure whether it would work, but it is my best shot ;-)
In Google Maps V3, the little bit of magic you need is documented here:
https://developers.google.com/maps/documentation/javascript/reference#Map
under events
Developers should trigger this event on the map when the div changes
size: google.maps.event.trigger(map, 'resize')
The trick is knowing when to call this which will be situational depending on your code. If you're using Bootstrap 3 Modals, this works beautifully.
$("#modal-map")
.modal()
.on("shown.bs.modal", function() {
google.maps.event.trigger(gmap, 'resize');
});
Where gmap is the google.maps.Map object you created.
I faced same issue when i tried to load google map in dialog. It was like google map was not rendered properly. so i find out below solution which may be solve your problem.
I have triggered google map resize event after initialize dialog please check below snipped code.
google.maps.event.trigger(map, 'resize', function () {
// your callback content
});
Example:
I have loaded map by ajax call then initialized dialog and at last triggered google map resize event.
$.ajax({
url:"map.php",
type:"POST",
success:function(data){
$("#inlineEditForm").html(data);
$('#inlineEditPopUp').dialog('open');
google.maps.event.trigger(map, 'resize', function () {
// your callback content
});
}
});
If you are using the jQuery plugin goMap, then you should use:
google.maps.event.trigger($.goMap.map, 'resize');
Although you should wrap this in an event so that it runs when the map is shown.
This how i do it in my code :
$(document).on('click', '#mapClicker', 'initmap', function() {
setTimeout(function() {
google.maps.event.trigger($.goMap.map, 'resize');
$.goMap.fitBounds();
}, 100)
});
I know this question is a bit old, but I just came across a similar problem. However, in my case, I was setting the map to be loaded from the body (for a full screen effect) within an iframe.
Like Jay mentioned on his answer a width and height must be specified which I had not done then.
I changed:
<body style="margin:0;">
to:
<body style="margin:0;width:100%;height:100%">
and now it loads perfectly on Chrome, Firefox and Internet Explorer 10.
Hopefully this helps anyone out there who also came across this problem. You must specify width and height for it to work across different clients.
Regards
I had the same problem and solved it simply by changing the width of the containing div to "px" instead of "%" (e.g width="700px" instead of "80%"). I guess that google can do better size calculation that way... I don't guarantee for this but it helped me
I had this issue and I found the only solution (in my instance) was to trigger the resize inline after the element. I can't say why but I found a thread where somebody also had this solution. (sorry no ref.) My setup was a tad different; it was from a jQueryMobile injected page so the late instantiation may have something to do with my issue. Hopefully this helps someone.
<div id="my-map"></div>
<script type="text/javascript">
$('#my-map').height($("#my-map-container").height());
$('#my-map').width($("#my-map-container").width());
google.maps.event.trigger($('#my-map'), 'resize');
</script>
In my case, same issues for Mac devices on:
Safari 5.1.7 (Os Windows 10[Sorry])
Safari 5.1 (Ipad 1 [Old Sorry])
Safari 10 (Iphone 6 Plus)
Here my solution work for me:
1) capture Browser width detect.min.js
2) change attr style width parameter
3) resize map
/* Of course insert detect.min.js and Jquery in your HTML ;)*/
var user = detect.parse(navigator.userAgent);
var browserFamily=user.browser.family;
var browserVersion=user.browser.version;
if ( browserFamille=="Mobile Safari" || browserVersion.substr(0,3)=="5.1") {
canvasWidth = $(window).width(),
$(".macarte").attr("style","width:"+canvasWidth+"px")
google.maps.event.trigger(map, 'resize');
}
/* browserFamily returns "Mobile Safari" for tablet and mobile devices; "Safari" for desktop devices */
I faced the same issue when setting the map centre manually. I solved it by the below code:
google.maps.event.trigger(map, "center_changed");
function initialize(lon,lat) {
var largeLatlng = new google.maps.LatLng(lon,lat);
var largeOptions = {zoom: 18, center: largeLatlng,mapTypeId: google.maps.MapTypeId.ROADMAP};
var largeMap = new google.maps.Map(document.getElementById("map"), largeOptions);
var largeMarker = new google.maps.Marker({position: largeLatlng, map:largeMap, title:"Cherrytrees"});
google.maps.event.addListenerOnce(largeMap, 'idle', function(){
google.maps.event.trigger(largeMap, 'resize');
largeMap.setCenter(largeLatlng);
});
largeMarker.setMap(largeMap);
}

Categories

Resources