Not able to load google map - javascript

I am trying to show the user's location obtained using geolocation API on google map.but the map is not loading.What am i doing wrong ?
$(document).ready(function(){
trackLocation()
})
//Track the user's location with high accuracy
function trackLocation(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(
successFunction,
errorFunction,
{enableHighAccuracy : true,
timeout:1000 * 10 * 100,
maximumAge:0
}
)
}
}
function successFunction(position){
plotMap(position)
}
function errorFunction(error){
alert(error)
}
function plotMap(position){
var location = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude)
alert('created locaction')
var plotOptions = {
center: location,
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
alert('created options')
var map = new google.maps.Map(document.getElementById('map_canvas'),plotOptions)
alert('created map')
}
and the html is
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="{{STATIC_URL}}jquery.min.js"></script>
<script type="text/javascript" src="{{STATIC_URL}}javascript_posted_above.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
</head>
<body>
Hi
<div id="map_canvas" style="width:100%; height:100%;"></div>
</body>
</html>

Take a look at this jsFiddle. The only differences between this and yours are the removal of the static js references and added the CSS. Without that CSS the map doesn't appear to display. I have never experienced this problem when using the Maps Api, perhaps I just added this CSS without thinking.
The CSS was taken from the HelloWorld tutorial on the docs.

here is my fiddle, I changed a few things:
First off all, I changed Alert to Console.log, which is important
since it is a non-obstructive way of logging, alert stops script
excecution and is not reliable.
I removed the google map script tag, and dynamically added it to the page in the document.ready handler, I also added a callback function "&callback=trackLocation", the JSON-P loaded script from Google will run the function with that name, when its executed.
I attached the function trackLocation(), directly to the window object, so it would be found by the script loaded from Google.
I changed the height of your map_canvas to 500px, instead of 100%, there seems to be an issue stretching a map. My first google search gave me: http://forum.jquery.com/topic/google-map-not-stretching-properly-when-width-set-to-100 you could do more research with that.
Good luck with your map!

Have you tried calling googlemap.js before your .js in the html?

I was loading the Google Maps API like this:
function mapsjsready()
{
// mapsjs ready!
}
$(document).ready( function() {
var mapsjs = document.createElement( 'script' );
mapsjs.type = "text/javascript";
mapsjs.async = true;
mapsjs.src = "https://maps.googleapis.com/maps/api/js?sensor=false";
mapsjs.id = "mapsjs";
mapsjs.onload = mapsjsready;
// Only for IE 6 and 7
mapsjs.onreadystatechange = function()
{
if( this.readyState == 'complete' )
{
mapsjsready();
}
}
document.body.appendChild( mapsjs );
});
But it suddenly stopped working.
I found that adding the callback parameter somehow solved the problem :
function mapsjsready()
{
// mapsjs ready!
}
function mapsjsloaded()
{
// mapsjs loaded!
}
$(document).ready( function() {
var mapsjs = document.createElement( 'script' );
mapsjs.type = "text/javascript";
mapsjs.async = true;
mapsjs.src = "https://maps.googleapis.com/maps/api/js?sensor=false&callback=mapsjsloaded";
mapsjs.id = "mapsjs";
mapsjs.onload = mapsjsready;
// Only for IE 6 and 7
mapsjs.onreadystatechange = function()
{
if( this.readyState == 'complete' )
{
mapsjsready();
}
}
document.body.appendChild( mapsjs );
});
I don't understand why, but adding the callback parameter solved my problem.

Related

htmx: Load JS lib and execute function?

I do update a html fragment via htmx.
How to load a JS library which is needed for this new snippet?
How to execute a function after the snippet got loaded?
Example:
I want to show an joyful animation (confetti) after the html snippet got added to the page.
This means the browser needs to load this:
<script src="https://cdn.jsdelivr.net/npm/canvas-confetti#1.4.0/dist/confetti.browser.min.js"></script>
After loading above lib a JS function needs to get executed.
How to do this with htmx?
I found a solution. I guess it could get improved. Please leave a comment if you know a simpler way.
// lala.js
// this file gets loaded in the page (before the hx-post call)
function loadScript(url, callback) {
// https://stackoverflow.com/a/950146/633961
// Adding the script tag to the head as suggested before
var head = document.head;
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// Then bind the event to the callback function.
// There are several events for cross browser compatibility.
script.onreadystatechange = callback;
script.onload = callback;
// Fire the loading
head.appendChild(script);
};
document.body.addEventListener("confetti", function(evt){
var target = document.getElementsByClassName('htmx-settling')[0];
loadScript('https://cdn.jsdelivr.net/npm/canvas-confetti#1.4.0/dist/confetti.browser.min.js',
function () {
var myCanvas = document.createElement('canvas');
var rect = target.getBoundingClientRect();
myCanvas.setAttribute('style', 'position: absolute; top:' +
rect.top + 'px; left:' + rect.left + 'px');
target.appendChild(myCanvas);
var myConfetti = confetti.create(myCanvas, {
resize: true,
useWorker: true
});
myConfetti({
particleCount: 100,
spread: 160
// any other options from the global
// confetti function
})
})
})
On the server side I return the response like this (Django):
def confetti_hx(request):
...
response = HttpResponse(html)
response['HX-Trigger-After-Swap'] = 'confetti'
return response
Right now there is no way to load a new library on a page built in to htmx (this is a necessary feature IMO, please log an issue for it) so the confetti library should be included initially as part of your main site.
After you have included the external library in the main website, you can include a normal script tag that executes the confetti code necessary inline:
<script>
var myCanvas = document.createElement('canvas');
document.appendChild(myCanvas);
var myConfetti = confetti.create(myCanvas, {
resize: true,
useWorker: true
});
myConfetti({
particleCount: 100,
spread: 160
// any other options from the global
// confetti function
});
</script>
What I've been doing is use some Hyperscript to do something like this:
<script
src="https://cdn.jsdelivr.net/npm/canvas-confetti#1.4.0/dist/confetti.browser.min.js"
_="
on load
js
<enter code here>
end
end
"
></script>

Google Maps API not showing (fixed height / width does not solve)

Showing the map was working before but for some reason I can't really figure it stopped working.
Here is my html inclusion:
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=THIS_KEY_IS_CORRECT">
</script>
And here is my html:
(with style tags)
#map { height: 500px; }
<div id="map" > </div>
And my javascript
setTimeout(() => {
console.log("Running init map");
var map_div = document.getElementById("map");
var map_handler = new google.maps.Map(map_div, map_options);
console.log(map_handler);
},2000);
Here is the console log of map_handler:
ug {__gm: Yf, W: undefined, mapTypes: Object, features: Object, overlayMapTypes: _.td…}
So map_handler is actually returning something.
As I said, this used to work. For some reason it does not anymore.
Any idea why?
Thank you very much.
While this isn't the primary source of your issue - please note that you can't rely on setTimeout to tell you when the google maps JS API has been loaded. Use a callback:
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=THIS_KEY_IS_CORRECT&callback=myMapIsReady">
</script>
And then
<script>
var myMapIsReady = function() {
console.log("Running init map");
var map_div = document.getElementById("map");
var map_handler = new google.maps.Map(map_div, map_options);
console.log(map_handler);
};
</script>
Here's the question, why are you saying this isn't working? How is it not working? What do you see on your screen?
A hint might be what is map_options you haven't shown where it is defined and if you init a google map with no center latlng/zoom, you'll just see a grey block.

How to set default layer visible in openlayers 2

I have two layers and switcher in openlayers. After init immediately I would like to set second layer to be visible, but still showed first added layer.
I tried: setVisibility, setBaseLayer, but without successful.
Here is part of code:
var gmapLayer = new OpenLayers.Layer.Google("Google sattelite", { type: google.maps.MapTypeId.SATELLITE, visibility: false });
var gmapStreetLayer = new OpenLayers.Layer.Google("Google streets", { visibility: false });
map.addLayer(gmapLayer);
map.addLayer(gmapStreetLayer);
map.addControl(new OpenLayers.Control.LayerSwitcher());
After init I tried:
map.setBaseLayer(selLayer);
//or
selLayer.setVisibility(true);
Ok I found problem. I used setBaseLayer wrong because called to array see:
var selLayer = map.getLayersByName(selectedLayer);
if (selLayer !== null) {
map.setBaseLayer(selLayer); //<---Wrong
}
Right solutions is:
var selLayer = map.getLayersByName(selectedLayer);
if (selLayer !== null) {
map.setBaseLayer(selLayer[0]); //<--Good
}

2 or more async requests in javascript to load image or do anything else

Single request and response model at one time do not utilizes full network/internet bandwidth, thus resulting in low performance. (benchmark is of half speed utilization)
how to make this code use 2 or 3 or more async requests instead of one.(ajax)
or do i need multi threading? and is it possible in javascript?
(this is for making a video out of an ip )
every time the image changes on request. and yes i need to be async with multiple fetch requests (not single as i explained above) or you recomend threads?
<html>
<head> <script language="JavaScript">
// Global vars
img = 'http://pastebin.com/i/t.gif';
timeout = 1000;
next = 0;
function onLoad( ) {
setTimeout( 'reloadImage( )', timeout );
}
// Reloader
function reloadImage( ) {
next = ( new Date( ) ).getTime( ) + timeout;
document.images.dv.src = img + "?" + next;
}
</script>
</head>
<body>
<img src="img" name="dv" onLoad="onLoad( )">
</body>
</html>
and
<html>
<head>
</head>
<body>
<div id="container"></div>
<script language="JavaScript">
var canLoad = true;
var container = document.getElementById("container");
var image = document.createElement("img");
image.onload = function() {
canLoad = true;
console.log("Image reloaded.");
}
var imageUrl = "http://url/snapshot.jpg";
var fps = 2;
container.appendChild(image);
function loadImage() {
if (canLoad) {
canLoad = false;
var str = new Date().getTime();
image.setAttribute("src", imageUrl + "?" + str);
console.log("Reloaded now.");
} else {
console.log("Can't reload now.");
}
}
setInterval(loadImage, fps); // 30 fps
</script>
</body>
</html>
Not actually tested, and I think it'll very likely to cause a "stack overflow" eventually (if you directly implement it), but you may still give it a look:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function(){
var img="/*url*/";
var interval=50;
var pointer=0;
function showImg(image,idx)
{
if(idx<=pointer) return;
document.body.replaceChild(image,document.getElementsByTagName("img")[0]);
pointer=idx;
preload();
}
function preload()
{
var cache=null,idx=0;;
for(var i=0;i<5;i++)
{
idx=Date.now()+interval*(i+1);
cache=new Image();
cache.onload=(function(ele,idx){return function(){showImg(ele,idx);};})(cache,idx);
cache.src=img+"?"+idx;
}
}
window.onload=function(){
document.getElementsByTagName("img")[0].onload=preload;
document.getElementsByTagName("img")[0].src="/*initial url*/";
};
})();
</script>
</head>
<body>
<img />
</body>
</html>
What it does:
When the initial image loads, preload() is called;
When preload() is called, it creates 5 image cache, and each attach its onload event to showImg();
When showImg() is called, it checks whether the current index is behind current pointer, and if it does, replace the current image with this new one, and call preload();
Back to 2.
If you really going to implement this, increase interval and decrease i<5. Also, a caching/queuing mechanic to check how many images in cache/queue before loading the next queue would be nice.
Also, notice that I didn't use getElementById to get the image, because there will be no stable ID.

Fading script will not work in IE?

I'm pretty new to Javascript and have been trying to achieve some fading effects on a website.
I've managed to hammer together the effects I want and everything's working fine on Firefox & Safari. However IE doesn't like it. The first script to change the background colour works but the second script to fade in the content does nothing.
I'm calling the scripts from the head as follows:
window.onload=siteIntro;
And the Javacript which is not working is here. Any help or suggestions would be appreciated, the live site can be viewed if needed.
Many Thanks
// ################# Fade Divs ###############################
function Fade(objID,CurrentAlpha,TargetAlpha,steps){
var obj = document.getElementById(objID);
CurrentAlpha = parseInt(CurrentAlpha);
if (isNaN(CurrentAlpha)){
CurrentAlpha = parseInt(obj.style.opacity*100);
if (isNaN(CurrentAlpha))CurrentAlpha=100;
}
var DeltaAlpha=parseInt((CurrentAlpha-TargetAlpha)/steps);
var NewAlpha = CurrentAlpha - DeltaAlpha;
if (NewAlpha == 100 && (navigator.userAgent.indexOf('Gecko') != -1 && navigator.userAgent.indexOf('Safari') == -1)) NewAlpha = 99.99;
obj.style.opacity = (NewAlpha / 100);
obj.style.MozOpacity = obj.style.opacity;
obj.style.KhtmlOpacity = obj.style.opacity;
obj.style.filter = 'alpha(opacity='+NewAlpha+')';
if (steps>1){
setTimeout('Fade("'+objID+'",'+NewAlpha+','+TargetAlpha+','+(steps-1)+')', 50);
}
}
// ################# Toggle content div visibility ###############################
function mainVis(showMain) {
document.getElementById(showMain).style.visibility ="visible";
}
function pageSwitch(show0, hide0, hide1, hide2, hide3) {
document.getElementById(show0).style.visibility ="visible";
document.getElementById(hide0).style.visibility ="hidden";
document.getElementById(hide1).style.visibility ="hidden";
document.getElementById(hide2).style.visibility ="hidden";
document.getElementById(hide3).style.visibility ="hidden";
}
function pg1() {
pageSwitch('prices', 'icon', 'about', 'map', 'news');
Fade('prices','0',100,30)
}
function pg2() {
pageSwitch('about', 'icon', 'prices', 'map', 'news');
Fade('about','0',100,30)
}
function pg3() {
pageSwitch('map', 'icon', 'about', 'prices', 'news');
Fade('map','0',100,30)
}
function pg4() {
pageSwitch('news', 'icon', 'map', 'about', 'prices');
Fade('news','0',100,30)
}
// ################# Site Intro Functions ###############################
function siteIntro() {
setTimeout("NLBfadeBg('b1','#FFFFFF','#000000','3000')",2000);
mainVis('main');
setTimeout("Fade('main','',100,30)",5000);
}
MS filters only apply to elements that "have layout".
To force layout, you can give the element a width or a height, or use the old zoom: 1; trick.
Not sure if this is the cause of your problems, but you could try it.
You can read more about hasLayout here.
Another thing, instead of:
setTimeout('Fade("'+objID+'",'+NewAlpha+','+TargetAlpha+','+(steps-1)+')', 50)`
you can simply write:
setTimeout(function() { Fade(objID, NewAlpha, TargetAlpha, steps-1); }, 50)`
Unless you are doing it just for fun and/or learning, just use an existing JS library instead of re-inventing the wheel.
Maybe you can take advantage of an out-of-the-box cross browser script like this
http://brainerror.net/scripts/javascript/blendtrans/
Or use jQuery (which is great with animating and effects) or any other JS library
This might not be an answer you are looking for, but you shouldn't be doing this: you can use jQuery to do this for you. One or two lines of code, and it is cross browser compatible.

Categories

Resources