I'm using the Bing Maps Android SDK and I'm looking for a way to click on the polygons that I have created and show an infobox. I've been able to accomplish this for a pushpin, but not for a polygon. I have seen this answer, but my app needs will make hundreds of such polygons, and I'm looking for a faster solution using the addHandler method on polygons. I know this is possible for the AJAX v7 flavour of the SDK, which is the underlying base of the Android SDK.
The code I tried for the AJAX version (tested using this emulator.)
map.entities.clear();
latlon = map.getCenter();
var polygon = new Microsoft.Maps.Polygon([new Microsoft.Maps.Location(latlon.latitude, latlon.longitude-0.15), new Microsoft.Maps.Location(latlon.latitude+0.1, latlon.longitude-0.05), new Microsoft.Maps.Location(latlon.latitude+0.1, latlon.longitude+0.05), new Microsoft.Maps.Location(latlon.latitude, latlon.longitude+0.15), new Microsoft.Maps.Location(latlon.latitude-0.1, latlon.longitude+0.05), new Microsoft.Maps.Location(latlon.latitude-0.1, latlon.longitude-0.05), new Microsoft.Maps.Location(latlon.latitude, latlon.longitude-0.15)], null);
Microsoft.Maps.Events.addHandler(polygon, 'click', DisplayInfo);
map.setView( {zoom:10});
map.entities.push(polygon);
function DisplayInfo (e) {
var vertices = e.target.getLocations();
var verticeCenter = new Microsoft.Maps.Location(0,0);
//Calculating location of center
for (i=0; i<vertices.length-1; i++) {
verticeCenter.latitude = verticeCenter.latitude + vertices[i].latitude;
verticeCenter.longitude = verticeCenter.longitude + vertices[i].longitude;
}
verticeCenter.latitude = verticeCenter.latitude / (vertices.length - 1);
verticeCenter.longitude = verticeCenter.longitude / (vertices.length - 1);
defaultInfobox = new Microsoft.Maps.Infobox(verticeCenter, {width: 200, height: 50} );
map.entities.push(defaultInfobox);
}
However, I pushed a similar code to the BingMapsAndroid.js from the assets folder of the SDK, but that doesn't work. The handler is attached, as I checked using the hasHandler method. Touches are recorded and their lat and long values are sent to the log, but the polygon event is not evoked even when the touch lies inside a polygon.
Polygon test function in BingMapsAndroid.js:
this.PolygonTest = function() {
_map.entities.clear();
latlon = new Microsoft.Maps.Location(1,1);
console.log("Polygon test function");
var polygon = new Microsoft.Maps.Polygon([new Microsoft.Maps.Location(latlon.latitude, latlon.longitude-0.15), new Microsoft.Maps.Location(latlon.latitude+0.1, latlon.longitude-0.05), new Microsoft.Maps.Location(latlon.latitude+0.1, latlon.longitude+0.05), new Microsoft.Maps.Location(latlon.latitude, latlon.longitude+0.15), new Microsoft.Maps.Location(latlon.latitude-0.1, latlon.longitude+0.05), new Microsoft.Maps.Location(latlon.latitude-0.1, latlon.longitude-0.05), new Microsoft.Maps.Location(latlon.latitude, latlon.longitude-0.15)], null);
try {
Microsoft.Maps.Events.addHandler(polygon, 'click', function(e) { console.log("Polygon click!"); }); //This is never evoked
Microsoft.Maps.Events.addHandler(_map, 'click', function(e) { var point = new MM.Point(e.getX(), e.getY()); var loc = e.target.tryPixelToLocation(point); console.log("lat: " + loc.latitude + ", lon: " + loc.longitude); });
} catch(e) {
alert("Error");
}
_map.setView( {zoom:10});
_map.entities.push(polygon);
if (Microsoft.Maps.Events.hasHandler(polygon,'click')) {
console.log("Polygon has click handler."); //This works
}
//This function should be added to the click handler for polygon. I'll add it when I know the handler works.
function DisplayInfo (e) {
console.log("Polygon has been clicked.");
var vertices = e.target.getLocations();
var verticeCenter = new Microsoft.Maps.Location(0,0);
for (i=0; i<vertices.length-1; i++) {
verticeCenter.latitude = verticeCenter.latitude + vertices[i].latitude;
verticeCenter.longitude = verticeCenter.longitude + vertices[i].longitude;
}
verticeCenter.latitude = verticeCenter.latitude / (vertices.length - 1);
verticeCenter.longitude = verticeCenter.longitude / (vertices.length - 1);
defaultInfobox = new Microsoft.Maps.Infobox(verticeCenter, { width: 200, height: 50 });
_map.entities.push(defaultInfobox);
}
}
After much testing, I found the issue lies in Android. I tried the code on Bing Maps Interactive SDK for AjaxV7 and these are my results:
Desktop browsers: works (as written in the question)
iPhone 4S: works
Android 2.3.4 with default browser: does not work
Android 2.3.4 with Opera: works
Android ICS with Opera: works
Android ICS with default browser: does not work
Related
I am developing an ionic app to be run on Android. On a particular screen, I have a google maps and a search box. I have used the phone gap plugin for the google maps to get the native map instead of using Google Maps Javascript API as it is too slow.
The search box is autocomplete to get places from google using the following code -
input = document.getElementById 'search-input'
autocomplete = new google.maps.places.Autocomplete(input)
This turns the input field with autocomplete for places from google. The problem is that I am not able to select any of the options from the autocomplete dropdown.
My HTML code -
<ion-content scroll="false">
<div id="searchBox">
<input id="search-input">
</div>
<div id="map-canvas">
</ion-content>
The map-canvas holds the map. I tried adding ng-focus="disableTap()" to input search-input.
disableTap = ->
container = document.getElementsByClassName 'pac-container'
angular.element(container).attr 'data-tap-disabled', 'true'
angular.element(container).on 'click', ->
document.getElementById('search-input').blur()
I found this solutions at this link
But this does not work. Any inputs here? I'm at my wits end here.
The below worked for me.
From user #TillaTheHun0 :
.controller('MyCtrl', function($scope) {
$scope.disableTap = function(){
container = document.getElementsByClassName('pac-container');
// disable ionic data tab
angular.element(container).attr('data-tap-disabled', 'true');
// leave input field if google-address-entry is selected
angular.element(container).on("click", function(){
document.getElementById('searchBar').blur();
});
};
})
Okay i found the solution, this will make you able to select on mobile
add this after creating your map
$$('body').on('touchstart','.pac-container', function(e){
e.stopImmediatePropagation();
})
i will also post my full code in case you're confused :
var myLatLng = {lat: 36.5802466, lng: 127.95776367};
document.getElementById('qkp-lat').value = myLatLng.lat;
document.getElementById('qkp-lng').value = myLatLng.lng;
window.postmap = new google.maps.Map(document.getElementById('postmap'), {
center: myLatLng,
zoom: 6,
mapTypeControl: false,
streetViewControl: false,
disableDefaultUI: true,
mapTypeId: 'roadmap'
});
// GOOGLE MAP RESPONSIVENESS
google.maps.event.addDomListener(window, "resize", function() {
var center = postmap.getCenter();
google.maps.event.trigger(postmap, "resize");
postmap.setCenter(center);
});
//MARKER
window.PostAdMarker = new google.maps.Marker({
map: postmap,
position:myLatLng,
draggable: true,
anchorPoint: new google.maps.Point(0, -29)
});
//LOAD FROM CURRENT CITY
var geocoder = new google.maps.Geocoder();
//AFTER DRAG AND DROP SHOWS THE LAT AND LONG
google.maps.event.addListener(PostAdMarker, 'dragend', function (event) {
var latlng = {lat: this.getPosition().lat(), lng: this.getPosition().lng()};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[1]) {
// saving to dom
document.getElementById('qkp-lat').value = latlng.lat;
document.getElementById('qkp-lng').value = latlng.lng;
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
});
var getlocDiv = document.createElement('div');
var getlocvar = new getloc(getlocDiv, postmap);
getlocDiv.index = 1;
postmap.controls[google.maps.ControlPosition.TOP_RIGHT].push(getlocDiv);
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
postmap.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
postmap.addListener('bounds_changed', function() {
searchBox.setBounds(postmap.getBounds());
});
var markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: postmap,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
postmap.fitBounds(bounds);
});
$$('body').on('touchstart','.pac-container', function(e){
e.stopImmediatePropagation();
})
original post: ( before fix )..
I develop an application (transformer.html) with XDK (ThreeJS and WebGL ) to control another application. The communication is established via a WebService (VB ASP.Net). The first version of this transformer.html had NO WebGL neither crosswalk. In debug and emulator-mode all is fine. Also compiled as a legacy hybrid mobile APK and published to my Samsung Galaxy Tab 3 without any problems. The problems pop up when I implement CrossWalk AND XMLHTTPRequest in my app.
The same origin policy seems not to be a problem. I placed this on web server side (in web.config).
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
As said - the constellation Transformer-APP on Tablet -- WebService --- TargetWebApplication is running perfectly in my local network!
The Problem:
The problem I run into came up with implementing a simple WebGL graphic. Everything is running perfectly in simulation and debug, and when I just run this in a Firefox browser. But when I build an APK this combination (CrossWalk & XMLHTTPRequest) fails!
*kristina/14.03.15: it´s working now. i consequently used this XDK-example: https://github.com/gomobile/sample-webgl-threejs
i took my httprequest in and it was working fine!*
Before:
XMLHTTPRequest (or even the POST via jQuery!) work fine under Android Legacy build. I could make the APK running but there was no Crosswalk WebGL graphic visible on my app. So HTTP Post was OK, but not Crosswalk. I´m wondering if it is possible to build a legacy App with Crosswalk. Even with the XDK's own Crosswalk demo, I was not able to build as a hybrid Legacy APK.
CrossWalk was OK on my app when I build with CrossWalk for Android, but, in this case, XMLHTTPRequest seems not possible. My connection to the WebService fails; I got a 404. But, as I said, all communication should be there, as in other modes (legacy, emulation, browser, whatever...), its working.
kristina/14.03.15: XDK recomment to build it in Android/Crosswalk. This is working NOW. The trick is to set specific host parameters in the build section!
<access origin="*"/>
( handle with care. e.g. reduce this to limited hosts! my setup only is working in my smal local environment. This way it´s ok for me )
those info was very helpful during the errorTracking:
*https://software.intel.com/en-us/xdk/docs/adding-special-build-options-to-your-xdk-cordova-app-with-the-intelxdk-config-additions-xml-file
https://software.intel.com/en-us/xdk/docs/using-the-cordova-for-android-ios-etc-build-option
http://www.ilinsky.com/articles/XMLHttpRequest/#usage
This was NOT very helpful - as in XDK/cordova/Crosswalk the manifest.json seem not effect anything(!?):
https://crosswalk-project.org/documentation/manifest/content_security_policy.html
As so soften it was the same-origine topic i struggled..
Many Thanks to Paul (Intel) who gave me the final hint :-)
Now the construction
CrossWalk - WebGL - XMLHttpRequest - Webservice is working perfect
*
My Setup:
XDK1826 (latest release I got automatically!)
Samsung Galaxy Tab 3
If you need more info please let me know.
THIS code is running after the fixes:
main.js::
/*jslint browser:true, devel:true, white:true, vars:true, eqeq:true */
/*global THREE:false, requestAnimationFrame:false*/
/*
* Based on http://threejs.org/examples/canvas_geometry_cube.html
*/
document.addEventListener ('DOMContentLoaded', function () {
var camera, scene, renderer;
var cube, plane;
var targetRotation = 0;
var targetRotationOnMouseDown = 0;
var mouseX = 0;
var mouseXOnMouseDown = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var auto_timer = 0;
init();
animate();
function init() {
renderer = new THREE.WebGLRenderer( { antialias: true, alpha: true, devicePixelRatio: 1 } );
renderer.setSize (window.innerWidth, window.innerHeight);
document.body.appendChild (renderer.domElement);
camera = new THREE.PerspectiveCamera (
70, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.y = 150;
camera.position.z = 500;
scene = new THREE.Scene();
// Cube
var geometry_cube = new THREE.CubeGeometry (200, 200, 200);
var texture = THREE.ImageUtils.loadTexture ('textures/crosswalk.png');//Works on mobile Android NOT in Browser or Intel XDK
texture.anisotropy = renderer.getMaxAnisotropy ();
var material_cube = new THREE.MeshBasicMaterial ( { map: texture } );
cube = new THREE.Mesh (geometry_cube, material_cube);
cube.position.y = 150;
scene.add( cube );
// Plane
var geometry_plane = new THREE.PlaneGeometry (180, 180);
geometry_plane.applyMatrix (new THREE.Matrix4 ().makeRotationX (-Math.PI / 2));
var material_plane = new THREE.MeshBasicMaterial ( { color: 0xde613e } );
plane = new THREE.Mesh (geometry_plane, material_plane);
scene.add (plane);
document.addEventListener ('mousedown', onDocumentMouseDown, false);
document.addEventListener ('touchstart', onDocumentTouchStart, false);
document.addEventListener ('touchmove', onDocumentTouchMove, false);
// Generic setup
window.addEventListener ('resize', onWindowResize, false);
}
function onWindowResize () {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix ();
renderer.setSize (window.innerWidth, window.innerHeight);
}
function stopAutoRotate () {
if (auto_timer)
window.clearTimeout (auto_timer);
auto_timer = window.setTimeout (startAutoRotate, 1000);
}
function startAutoRotate () {
auto_timer = 0;
}
function animate () {
requestAnimationFrame (animate);
plane.rotation.y = cube.rotation.y += (targetRotation - cube.rotation.y) * 0.05;
if (auto_timer === 0) {
targetRotation += 0.025;
}
renderer.render (scene, camera);
}
function onDocumentMouseDown (e) {
e.preventDefault();
document.addEventListener ('mousemove', onDocumentMouseMove, false);
document.addEventListener ('mouseup', onDocumentMouseUp, false);
document.addEventListener ('mouseout', onDocumentMouseOut, false);
mouseXOnMouseDown = e.clientX - windowHalfX;
targetRotationOnMouseDown = targetRotation;
stopAutoRotate ();
}
function onDocumentMouseMove (e) {
mouseX = e.clientX - windowHalfX;
targetRotation = targetRotationOnMouseDown +
(mouseX - mouseXOnMouseDown) * 0.02;
stopAutoRotate ();
}
function onDocumentMouseUp (e) {
document.removeEventListener ('mousemove', onDocumentMouseMove, false);
document.removeEventListener ('mouseup', onDocumentMouseUp, false);
document.removeEventListener ( 'mouseout', onDocumentMouseOut, false);
stopAutoRotate ();
}
function onDocumentMouseOut (e) {
document.removeEventListener ('mousemove', onDocumentMouseMove, false);
document.removeEventListener ('mouseup', onDocumentMouseUp, false);
document.removeEventListener ('mouseout', onDocumentMouseOut, false);
stopAutoRotate ();
}
function onDocumentTouchStart (e) {
if (e.touches.length === 1) {
e.preventDefault ();
miniHttpTest();
getSphereParametersWSxhr();
mouseXOnMouseDown = e.touches[ 0 ].pageX - windowHalfX;
targetRotationOnMouseDown = targetRotation;
stopAutoRotate ();
}
}
function onDocumentTouchMove (e) {
if (e.touches.length === 1) {
e.preventDefault ();
mouseX = e.touches[0].pageX - windowHalfX;
targetRotation = targetRotationOnMouseDown +
(mouseX - mouseXOnMouseDown) * 0.05;
stopAutoRotate ();
}
}
});
function XHRObject() {
var xhr;
xhr = new XMLHttpRequest();
xhr.onerror = function () {};
xhr.onstart = function () {};
xhr.success = function () {};
return xhr;
}
function getSphereParametersWSxhr() {
var url = "http://192.444.2.444/transporter.asmx/getVideoCubeParameters";
xhr = new XMLHttpRequest();
var params = "";
console.log(xhr);
alert("----------------------------- getSphereParametersWSxhr - before open POST : " + xhr);
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// forbidden xhr.setRequestHeader("Content-length", params.length);
alert("after open POST : " + xhr);
try {
xhr.onreadystatechange = function () {
alert("xhr.readyState == " + xhr.readyState + " xhr.status == " + xhr.status + " xhr.statusText: " + xhr.statusText + " xhr.responseText" + xhr.responseText);
if (xhr.readyState == 2 && xhr.status == 404) {
console.log("404 page not found: " + xhr);
alert("404 page not found: " + xhr);
}
if (xhr.readyState == 3) {
console.log("ready state 3: " + xhr.statusText + " " + xhr.status);
alert("ready state 3: " + xhr.statusText + " " + xhr.status);
}
if (xhr.readyState == 4) { //&& xhr.status == 200
console.log("ready state 4: " + xhr.statusText + " " + xhr.responseText);
alert("ready state 4: " + xhr.statusText + " " + xhr.responseText);
var erg1 = xhr.responseXML.getElementsByTagName("videoCubeSizeX")[0].textContent;
var stringList = erg1.split(";");
console.log(erg1);
alert("videoCubeSizeX: " + erg1);
alert(xhr.responseText);
}
}
xhr.send(params);
} catch (e) {
console.log("XHR Post : " + e);
alert("XHR Post : " + e);
}
}
function miniHttpTest() {
alert("miniHttpTest: mit GET ");
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://crosswalk-project.org/", true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
alert("ready state 4: " + xhr.statusText + " " + xhr.responseText);
}
}
xhr.send();
}
I'm working on a simple Alloy app. I have a view I want to move back and forth horizontally (thus to move and then return to its original position).
I wrote this function
function move(view) {
var origin = view.getCenter();
console.log("origin ", origin);
console.log("rect ", view.getRect());
var forth = Titanium.UI.createAnimation();
forth.duration = 700;
forth.center = {
x: 0
};
forth.addEventListener('complete', function() {
view.animate(back);
});
var back = Titanium.UI.createAnimation();
back.duration = 300;
back.center = {
x: origin.x
};
back.addEventListener('complete', function() {
alert('completed');
});
view.animate(forth);
}
I you run it, it crashes at x: origin.x because origin is undefined. Moreover, both view.center and view.rect are undefined, thus it's impossible for me to store the original position.
Any help?
Thanks
PS: Code has been tested on iOS simulator, although is meant to be Android and iOS compatible.
Why dont you just animate the left position and work with the view.getRect() ?
var origin = view.getRect();
//console.log("origin ", origin);
console.log("rect ", view.getRect());
var forth = Titanium.UI.createAnimation();
forth.duration = 5000;
forth.left = 0;
forth.addEventListener('complete', function() {
view.animate(back);
});
var back = Titanium.UI.createAnimation();
back.duration = 5000;
back.left = origin.x;
back.addEventListener('complete', function() {
alert('completed');
});
view.animate(forth);
i downloaded the SDK of Wikitude 3.1, installed the samples into my Eclipse workspace and on my Gnexus everything works. I divide the questions in points so could be easier to answer:
I added the "onMarkerSelectedFn" method into the "limitingVisiblePois.js" file because i wanted to have my POIs clickable and when clicked, appear the information page like the 5.1 example. I added the method but it doesn't work and i haven't understand where i'm making mistakes. Each other file is the same for the 5.x samples.
Code of "limitingVisiblePois.js" edited by me
var World = {
markerDrawable_idle: new AR.ImageResource("assets/marker_idle.png"),
markerDrawable_selected: new AR.ImageResource("assets/marker_selected.png"),
markerDrawable_directionIndicator: new AR.ImageResource("assets/indi.png"),
markerList: [],
// called to inject new POI data
loadPoisFromJsonData: function loadPoisFromJsonDataFn(poiData) {
PoiRadar.show();
document.getElementById("statusElement").innerHTML = 'Loading JSON objects';
var poiImage = new AR.ImageResource("img/marker.png", {
onError: World.errorLoadingImage
});
// TODO: call single POI-creation statement instead
for (var i = 0; i < poiData.length; i++) {
var singlePoi = {
//EDIT BRUS: adding the ID of each POIs
"id": poiData[i].id,
"latitude": parseFloat(poiData[i].latitude),
"longitude": parseFloat(poiData[i].longitude),
"altitude": parseFloat(poiData[i].altitude),
"title": poiData[i].name,
"description": poiData[i].description
};
World.markerList.push(new Marker(singlePoi));
}
document.getElementById("statusElement").innerHTML = 'JSON objects loaded properly';
},
// user's latest known location, accessible via userLocation.latitude, userLocation.longitude, userLocation.altitude
userLocation: null,
// location updates
locationChanged: function locationChangedFn(lat, lon, alt, acc) {
World.userLocation = {
'latitude': lat,
'longitude': lon,
'altitude': alt,
'accuracy': acc
};
},
//EDIT BRUS: Adding onMarkerSelected function
onMarkerSelected: function onMarkerSelectedFn(marker) {
// notify native environment
document.location = "architectsdk://markerselected?id=" + marker.poiData.id;
},
// called from slider.js every time the slider value changes
onSliderChanged: function onSliderChangedFn(value) {
if (value > 0) {
var valueMeters = value * 1000;
PoiRadar.setMaxDistance(valueMeters);
AR.context.scene.cullingDistance = valueMeters;
}
}
};
// forward locationChanges to custom function
AR.context.onLocationChanged = World.locationChanged;
2) I wasn't able to understand where the POIs latlong coordinates where declareated. In the same code posted ahead, there is the function
loadPoisFromJsonData: function loadPoisFromJsonDataFn(poiData)
but i don't understand how the poiData are taken.
I used the last 3.1 SDK in Android and phonegap.
thanks in advance,
Kind regards
Brus
PhoneGap Plugin samples are yet not in sync with those from the native SDK.
Whereat the current "HelloWorld" sample in PhoneGap Plugin requests POI-Data from a webservice the sample you pointed out is from the Android SDK and passes POI-data from native Android via "architectView.callJavaScript('loadPoisFromJsonData(...)')".
Both are making use of the same method to parse POI data, PhoneGap sample uses it e.g. that way
// request POI data
requestDataFromServer: function requestDataFromServerFn(lat, lon) {
var serverUrl = ServerInformation.POIDATA_SERVER + "?" + ServerInformation.POIDATA_SERVER_ARG_LAT + "=" + lat + "&" + ServerInformation.POIDATA_SERVER_ARG_LON + "=" + lon + "&" + ServerInformation.POIDATA_SERVER_ARG_NR_POIS + "=20";
var jqxhr = $.getJSON(serverUrl, function(data) {
World.loadPoisFromJsonData(data);
})
.error(function(err) {
alert("JSON error occured! " + err.message);
})
.complete(function() {});
}
You may just add these lines in your locationChanged implementation to use places from a dummy-webserver (don't forget to define 'alreadyRequestedData= false;' )
if (!World.alreadyRequestedData) {
World.requestDataFromServer(lat, lon);
World.alreadyRequestedData = true;
}
Kind regards,
Andreas
Original Title but too long for post:
"ASP.NET MVC 4, Razor, JQuery, JQueryMobile, Problems with Mobiscroll - orientationchange and access address bar crashes some mobile browsers. Changing scroller width and height does not work on some phones."
The crash issue happens on Android 2.1.
It does not happen on iPhone, HTC EVO 4G LTE or other HTCs.
Changing the scroller width and height does not work on HTCs. If I change to landscape then the scroller is the same size as it should be in portrait. If I change it back to portrait then the scroller is the size it should have been in landscape.
Here is the JQuery/Mobiscroll code:
function createDatePicker(selector){
if($("#input_date_1").scroller('isDisabled') != 'undefined'){
var scrollWidth = ($("div[id='main_content']").width()) / 4;
var scrollHeight = scrollWidth / 2.5;
$("#input_" + selector).scroller({
preset: 'date',
minDate: new Date(2000, 0, 1),
maxDate: new Date(2020, 11, 31),
theme: 'android',
display: 'inline',
mode: 'scroller',
dateOrder: 'mmddyy',
width: scrollWidth,
height: scrollHeight,
onChange: function (valueText, inst) {
var lbl = $("#lbl_" + selector);
var date = $("#input_" + selector).scroller('getDate');
lbl.text(date.toDateString());
}
});
}
function setDatePickerWidthAndHeight(){
var scrollWidth = ($("div[id='main_content']").width()) / 4;
var scrollHeight = scrollWidth / 2.5;
var selectorBase1 = "date_1";
$("#input_" + selectorBase1).eq(0).scroller('option', 'width', scrollWidth);
$("#input_" + selectorBase1).eq(0).scroller('option', 'height', scrollHeight);
}
$(function () {
createDatePicker('date_1');
$(window).bind('orientationchange', function (event) {
setTimeout(setDatePickerWidthAndHeight(),100);
});
});
I am including these scripts in #section scripts {} which is rendered at the bottom of the page ( not sure if that is relevant ).
Any help would be appreciated.
It turns out the problem was that the older Android phones do not like the resize event the way it was written above.... and newer phones did not like the orientationchange event. The code at this link made everything work perfectly:
http://paulirish.com/2009/throttled-smartresize-jquery-event-handler/
And here is how I used it:
//
// usage:
//$(window).smartresize(function () {
// // code that takes it easy...
//});
//http://paulirish.com/2009/throttled-smartresize-jquery-event-handler/
(function ($, sr) {
// debouncing function from John Hann
// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
var debounce = function (func, threshold, execAsap) {
var timeout;
return function debounced() {
var obj = this, args = arguments;
function delayed() {
if (!execAsap)
func.apply(obj, args);
timeout = null;
};
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 100);
};
}
// smartresize
jQuery.fn[sr] = function (fn, threshold, execAsap) { return fn ? this.bind('resize', debounce(fn, threshold, execAsap)) : this.trigger(sr); };
})(jQuery, 'smartresize');
$(function () {
createDatePicker('date_1');
$(window).smartresize(function () {
setDatePickerWidthAndHeight();
}, 200);
});
I found the link in the answer of this post: window.resize in jquery firing multiple times
Thanks!