Can't view Google Maps in HTML, Cordova - javascript

I'm trying to displayGoogle Maps on a html page in cordova.
The example code I'm trying to replicate is this one: https://developers.google.com/maps/documentation/javascript/examples/map-simple?hl=it
Here is my code:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Hello World</title>
</head>
<body>
<div class="app">
<div id="map-canvas"></div>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src=js/jquery-1.11.1.min.js></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script type="text/javascript" src="js/google_map.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
index.js (I used some alert() and every method was called)
var app = {
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
toIndex();
}
};
$(document).ready( function(){
app.initialize();
});
function toIndex(){
google_map.init();
}
google_map.js
the class which take care of the map
var google_map = (function(){
var _map;
var _$map_canvas;
function init(){
_$map_canvas = $('.app').find('#map-canvas');
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
_map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function getMap(){
return _map;
}
return {
init:init,
getMap:getMap
}
})();
and the index.css file
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
Instead of displaying the map, I see a white page.
Second question:
code here: http://jsfiddle.net/qbddfdk7/1/
This one doesn't work too, the problem is at line 14:
if I change it from
map = new google.maps.Map(map_canvas, mapOptions);
to
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
It will work, but I can't undesrstand why.

The problem with your second question is a timing issue.
You see, your inline javascript is in the <head>, so at the time var map_canvas = document.getElementById('map-canvas'); runs, the element with the id map-canvas is not loaded yet, so var map_canvas is set to null.
Moving the <script> tag to the bottom of the <body> element solves this issue. I've updated your jsFiddle accordingly.
As for your first issue, try Chrome Remote Debugging if available, or weinre. These will help you find the source of your problem.

I've had no luck using their recommendation to use percentages for the map-canvas. To ensure everything is working fine, hard-code the div tag to a fixed width and height.
Once you have the map displayed, then you'll need to write javascript to adjust the style width and height during the pagecreate or pageinit. You can then change the same properties during the orientationchange event.
There are several articles on the best way to find the screen size. I'm using:
function effectiveDeviceWidth(factor) {
var deviceWidth = window.orientation == 0 ? window.screen.width : window.screen.height;
// iOS returns available pixels, Android returns pixels / pixel ratio
// http://www.quirksmode.org/blog/archives/2012/07/more_about_devi.html
if (navigator.userAgent.indexOf('Android') >= 0 && window.devicePixelRatio) {
deviceWidth = deviceWidth / window.devicePixelRatio;
}
return parseInt(deviceWidth) * factor + 'px';
}
function effectiveDeviceHeight(factor) {
var deviceHeight = window.orientation == 0 ? window.screen.height : window.screen.width;
// iOS returns available pixels, Android returns pixels / pixel ratio
// http://www.quirksmode.org/blog/archives/2012/07/more_about_devi.html
if (navigator.userAgent.indexOf('Android') >= 0 && window.devicePixelRatio) {
deviceHeight = deviceHeight / window.devicePixelRatio;
}
return parseInt(deviceHeight) * factor + 'px';
}
$('#map-canvas').width(effectiveDeviceWidth(.8));
$('#map-canvas').height(effectiveDeviceHeight(.6));
Hope this helps.

The problem was in the css, in eclipse I corrcted the css to this:
html, body, #map-canvas {
height: 100%;
width: 100%;
position: relative;
z-index: -1;
margin: 0px;
padding: 0px
}
I'm new to web languages and I didn't know that I had to write css even for the hmtl and the body tag, as you can see those tag are missing from the code in the question.

Related

Geodesic Polylines in Here

I am trying to switch over from Google Maps to Here in a lot of my code. One thing that is hanging me up is the need for Geodesic lines versus "straight lines"
An example of this can be found here: http://www.2timothy42.org/Travel/?Mode=
There is another Stack Overflow question with the answer here but the link doesn't work anymore.
The example posted by HERE Developer Support gets you there, but the code has extra stuff in it that isn't necessary and it also has a few JS references that are relative and don't work once entered into my code.
This relates to one of the key difference I noticed between Google Maps API and HERE API is that Google Maps use one JS call, where as HERE has a few and if they aren't included correctly produce some issues.
HEAD
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.0/mapsjs-ui.css?dp-version=1533195059" />
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-core.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-service.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-ui.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-mapevents.js"></script>
<script src="https://tcs.ext.here.com/assets/geodesic-polyline-955f4bde9d216d0e89b88f4ba29c75fd1407f30f905380039e312976f3e30c88.js"></script>
BODY
<div id="map" style='width: 600px; height: 300px; border: 1px solid #000000;'></div>
<script type="text/javascript" charset="UTF-8" >
// Check whether the environment should use hi-res maps
var hidpi = ('devicePixelRatio' in window && devicePixelRatio > 1);
// check if the site was loaded via secure connection
var secure = (location.protocol === 'https:') ? true : false;
// Create a platform object to communicate with the HERE REST APIs
var platform = new H.service.Platform({
useCIT: true,
useHTTPS: secure,
app_id: 'API_APP_ID',
app_code: 'API_APP_CODE'
}),
maptypes = platform.createDefaultLayers(hidpi ? 512 : 256, hidpi ? 320 : null);
// Instantiate a map in the 'map' div, set the base map to normal
var map = new H.Map(document.getElementById('map'), maptypes.normal.map, {
center: {lat:32.00, lng:-110.00},
zoom: 1,
pixelRatio: hidpi ? 2 : 1
});
// Enable the map event system
var mapevents = new H.mapevents.MapEvents(map);
// Enable map interaction (pan, zoom, pinch-to-zoom)
var behavior = new H.mapevents.Behavior(mapevents);
// Enable the default UI
var ui = H.ui.UI.createDefault(map, maptypes);
window.addEventListener('resize', function() { map.getViewPort().resize(); });
var npoints = 100,
offset = 20;
// Tokyo -> san Francisco
add([35.68019,139.81194],[37.77712,-122.41964], {style: { strokeColor: "rgba(0,0,255,0.7)", lineWidth: 4}});
function add(s,e,options) {
var start_ll = new H.geo.Point(s[0],s[1]),
end_ll = new H.geo.Point(e[0],e[1]),
start_coord = {x: start_ll.lng, y:start_ll.lat},
end_coord = {x:end_ll.lng, y:end_ll.lat};
description = ''+s[0]+','+s[1]+'=>'+e[0]+','+e[1]+'',
gc0 = new arc.GreatCircle(start_coord,end_coord, {'name': 'line', 'color':'#ff7200','description':description}),
line0 = gc0.Arc(npoints,{offset:offset}),
strip = line0.strip();
map.addObject(new H.map.Polyline(strip, options));
}
</script>

Defining Position in Phaser

I'm making a very basic game in Javascript using the Phaser Directory. I have made games with Phaser many times before but this time I have come across an issue that is new to me and I've never had before. I've looked it up online and no one seems to have had this problem. In phaser it is telling me my "x" is not defined when I refer to x as a position. How would I go about defining x as a position or what error am I facing? I and currently using VS Code on mac with a Chrome browser and newest version of Phaser.
Thanks for the Help,
Murdoc
var game = new Phaser.Game(640, 360, Phaser.Auto);
var car1;
var GameState = {
preload: function(){
game.load.image("thecar1", "../assets/car_1.png");
//game.load.image("thecar2", "../assets/car_2.png");
//game.load.image("backgroundImg", "../assets/thebackground.png");
},
create: function(){
var car1 = game.add.sprite(200, 270, "thecar1");
//var car2 = game.add.sprite(200, 270, "thecar2");
/*game.input.keyboard.addKey(Phaser.Keyboard.W)
.onDown.add(car1Up);*/
game.input.keyboard.addKey(Phaser.Keyboard.A)
.onDown.add(car1Left);
/*game.input.keyboard.addKey(Phaser.Keyboard.S)
.onDown.add(car1Down);
game.input.keyboard.addKey(Phaser.Keyboard.D)
.onDown.add(car1Right);*/
},
update: function(){
}
};
function car1Left() {
car1.x = car1.x + 10;
}
game.state.add('GameState', GameState);
game.state.start('GameState');
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pixel Soccer</title>
<script src="phaser.js"></script>
<script src="main.js"></script>
<style>
body {
background: white;
margin: 0;
padding: 0;
}
body canvas {
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body>
</body>
</html>
You're declaring the same variable twice. You're dealing with what's called "variable shadowing". When you do var car1 = game.add.sprite(200, 270, "thecar1"); in the create() function, the scope changes to function-only and the variable with the sprite you assign to it is only available in the scope of that function. The error basically comes to tell you that var car1 that you declared outside of the function scope is undefined (which it is). Try doing just car1 = game.add.sprite(200, 270, "thecar1"); inside create() and it should be fine.

Phonegap plugin - imagePicker - Producing Error Message

I'm trying to add the phonegap imagePicker plugin to my app and am receiving the following error when I try to call the function:
"Uncaught TypeError: Cannot read property 'getPictures' of undefined",
source: file:///android_asset/www/js/main.js (85)
I installed the plugin using the CLI per the instructions. I have copied the .js to the appropriate folder and referenced it.
Here are the relevant sections of the different pages:
Html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<link href="jquerymobile/jquery.mobile-1.4.5.css" rel="stylesheet" type="text/css" />
<script src="js/jquery.js" type="text/javascript"></script>
<script src="jquerymobile/jquery.mobile-1.4.5.min.js" type="text/javascript"></script>
<script src="js/imagepicker.js" type="text/javascript"></script>
<script src="js/main.js"></script>
</head>
<body>
<!-- a bunch of irrelevant stuff -->
Upload
</body>
</html>
main.js:
$(document).on("pageshow", "#thepageinquestion", function() {
$("#btn_upload").click(function() {
window.imagePicker.getPictures( // <--- this is line 85
function(results) {
for (var i = 0; i < results.length; i++) {
console.log('Image URI: ' + results[i]);
}
}, function (error) {
console.log('Error: ' + error);
}
);
});
});
imagepicker.js:
cordova.define("com.synconset.imagepicker.ImagePicker", function(require, exports, module) { /*global cordova,window,console*/
/**
* An Image Picker plugin for Cordova
*
* Developed by Wymsee for Sync OnSet
*/
var ImagePicker = function() {
};
/*
* success - success callback
* fail - error callback
* options
* .maximumImagesCount - max images to be selected, defaults to 15. If this is set to 1,
* upon selection of a single image, the plugin will return it.
* .width - width to resize image to (if one of height/width is 0, will resize to fit the
* other while keeping aspect ratio, if both height and width are 0, the full size
* image will be returned)
* .height - height to resize image to
* .quality - quality of resized image, defaults to 100
*/
ImagePicker.prototype.getPictures = function(success, fail, options) {
if (!options) {
options = {};
}
var params = {
maximumImagesCount: options.maximumImagesCount ? options.maximumImagesCount : 15,
width: options.width ? options.width : 0,
height: options.height ? options.height : 0,
quality: options.quality ? options.quality : 100
};
return cordova.exec(success, fail, "ImagePicker", "getPictures", [params]);
};
window.imagePicker = new ImagePicker();
});
After beating this up for hours, finally realized the external javascript file wasn't loading. Rookie mistake, I had placed the reference to the script in the page header instead of within the data-role="page" tags.
Found the answer here:
JQuery Mobile Change Page doesnt load JS files

clientWidth and clientHeight delayed on Android default browser?

I am using jqtouch.js (with zepto.js) and testing the onorientationchange event:
http://www.ebi.ac.uk/~mp/test_orientation.html
<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
<!-- Local jqTouch -->
<link rel="stylesheet" href="lib/jqtouch-1.0-b4-rc/themes/css/apple.css" title="jQTouch">
<!-- <style type="text/css" media="screen">#import "lib/jqtouch-1.0-b4-rc/themes/css/jqtouch.css";</style> -->
<script src="lib/jqtouch-1.0-b4-rc/src/lib/zepto.min.js" type="text/javascript" charset="utf-8"></script>
<script src="lib/jqtouch-1.0-b4-rc/src/jqtouch.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
var jQT = new $.jQTouch({});
</script>
</head>
<body>
<h1>Hello World</h1>
<script>
window.onorientationchange = function() {
var w = document.documentElement.clientWidth;
var h = document.documentElement.clientHeight;
alert("WIDTH: " + w + " -- HEIGHT: " + h);
}
</script>
</body>
</html>
Opening this page with the default Android browser I get the clientWidth and clientHeight numbers reversed (when changing the orientation to landscape, I get more height than width, and vice-versa).
If I insert a short delay:
http://www.ebi.ac.uk/~mp/test_orientation_delay.html
<script>
window.onorientationchange = function() {
setTimeout(function() {
var w = document.documentElement.clientWidth;
var h = document.documentElement.clientHeight;
alert("WIDTH: " + w + " -- HEIGHT: " + h);
}, 500);
}
</script>
The clientWidth and clientHeight are properly retrieved.
This doesn't happen with Safari (iOS5) or Chrome (they don't need the short delay to display the correct numbers).
Is there an alternative way to safely retrieve these numbers consistently (without having to introduce an arbitrary delay that can be enough or not)?
M;
Possibly too late, but I think this has to do with the fact that when the event fires you're still looking at the BEFORE state. The new state will occur AFTER the event, as the event only tells you "I am ABOUT to change orientation, but didn't do it yet."

Why can't I get the naturalHeight/naturalWidth of an image in javascript/JQuery?

So I'm trying to do some very basic div re-sizing based on the properties of the image contained within it. I know I can do something really basic like set the background an padding around the image and achieve the same effect, but this is sort of a personal challenge.
The problem I am having is that when I try to fetch the naturalHeight or naturalWidth values of the image, I get a value of 0. However, when I try to fetch these values using the console, they return the correct values. Also, my resizeDiv() function is coming up as undefined in console.
Here's the code:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>kitten_resize - WesGilleland.com</title>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var kittens = new Array("100x100_kitten.jpeg","150x150_kitten.jpeg","200x150_kitten.jpeg");
$('#kittens').attr('src', kittens[0]); //set the image
function resizeDiv() {
var img = document.getElementById('kittens');
var imgH = img.naturalHeight;
var imgW = img.naturalWidth;
$('div').width(imgW);
$('div').height(imgH);
console.log('Current imgH: '+imgH);
console.log('Current imgW: '+imgW);
};
resizeDiv();
});
</script>
<style>
div {
background-color: black;
padding: 10px;
margin: auto;
}
</style>
</head>
<body>
<div>
<img id="kittens" src='' />
</div>
</body>
</html>
You can also find a working copy here: http://www.wesgilleland.com/projects/kitten_resize/
I feel like it's something very basic that I'm missing; I haven't fiddled with this stuff since my associate's degree a year ago. Thanks to anyone who can help!
That's because your image isn't yet loaded when you read the original dimensions.
You should read the dimensions when the image is loaded :
var img = $('#kittens')[0];
img.onload = resizeDiv;
img.src = kittens[0];

Categories

Resources