intel XDK camera view is not working - android

I am creating an augmented reality application using intel XDK.When I load the this app in the "Intel App Preview" app, I see a red background and no camera view when I hold my device in vertical position. Everything else seems to work.Why dont I see the camera view ?
This is my codes
<!doctype html>
<html>
<head>
<title>Nearby</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta name="Copyright" content="© 2013, Intel Corporation. All rights reserved." />
<meta name="Author" content="Nadeesha" />
<!--
* Copyright (c) 2013, Intel Corporation. All rights reserved.
* Please see http://software.intel.com/html5/license/samples
* and the included README.md file for license terms and conditions.
-->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="apple-mobile-web-app-capable" content="yes" />
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="lib/jquery/jquery-1.8.2.min.js"></script>
<script src="cordova.js"></script>
<script src="intelxdk.js"></script>
<script>
var pin = [
{"name":"RUSL", "lat":"8.3635595", "lng":"80.5042495"},
{"name":"Mihinthale", "lat":"8.35059440", "lng":"80.5169444"},
{"name":"Mihintale Railway Station", "lat":"8.3589425", "lng":"80.50174530"},
{"name":"Mihintale Forest Reserve", "lat":"8.3783333", "lng":"80.47916669"},
{"name":"Mihintale Wewa", "lat":"8.3613889", "lng":"80.5052777"},
{"name":"Mihintalekanda", "lat":"8.35000000", "lng":"80.500000"}
];
var markersArray = [], bounds;
var myLat = 0, myLng = 0;
var bearing, distance;
var dataStatus = 0;
// setup map and listen to deviceready
$( document ).ready(function() {
document.addEventListener("deviceready", onDeviceReady, false);
});
// start device compass, accelerometer and geolocation after deviceready
function onDeviceReady() {
navigator.splashscreen.hide();
setupMap();
// start cordova device sensors
startAccelerometer();
startCompass();
startGeolocation();
}
// start intel.xdk augmented reality mode, adds camera in background
function xdkStartAR(){
intel.xdk.display.startAR();
$('#arView').css('background-color','transparent');
$('body').css('background-color','transparent');
document.getElementById('body').style.background = "transparent";
}
// stop intel.xdk augmented reality mode
function xdkStopAR(){
intel.xdk.display.stopAR();
}
// setup google maps api
function setupMap(){
$("#map").height($(window).height()-60);
var mapOptions = {
zoom: 13,
mapTypeControl: false,
streetViewControl: false,
navigationControl: true,
scrollwheel: false,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
}
// toggle between list view and map view
function toggleView(){
if($(".listView").is(":visible")){
$(".listView").hide();
$("#map").height($(window).height()-60);
$(".mapView").fadeIn(function(){google.maps.event.trigger(map, "resize");map.fitBounds(bounds);});
$("#viewbtn").html("List");
} else {
$(".mapView").hide();
$(".listView").fadeIn();
$("#viewbtn").html("Map");
}
}
// get data from API and store in array, add to list view and create markers on map, calculate
function loadData(){
dataStatus = "loading";
markersArray = [];
bounds = new google.maps.LatLngBounds();
// add blue gps marker
var icon = new google.maps.MarkerImage('http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png',new google.maps.Size(30, 28),new google.maps.Point(0,0),new google.maps.Point(9, 28));
var gpsMarker = new google.maps.Marker({position: new google.maps.LatLng(myLat, myLng), map: map, title: "My Position", icon:icon});
bounds.extend(new google.maps.LatLng(myLat, myLng));
markersArray.push(gpsMarker);
// add all location markers to map and list view and array
for(var i=0; i< pin.length; i++){
$(".listItems").append("<div class='item'>"+pin[i].name+"</div>");
addMarker(i);
relativePosition(i);
}
map.fitBounds(bounds);
google.maps.event.trigger(map, "resize");
dataStatus = "loaded";
}
// add marker to map and in array
function addMarker(i){
var marker = new google.maps.Marker({position: new google.maps.LatLng(pin[i].lat, pin[i].lng), map: map, title: pin[i].name});
bounds.extend(new google.maps.LatLng(pin[i].lat, pin[i].lng));
markersArray.push(marker);
}
// clear all markers from map and array
function clearMarkers() {
while (markersArray.length) {
markersArray.pop().setMap(null);
}
}
// calulate distance and bearing value for each of the points wrt gps lat/lng
function relativePosition(i){
var pinLat = pin[i].lat;
var pinLng = pin[i].lng;
var dLat = (myLat-pinLat)* Math.PI / 180;
var dLon = (myLng-pinLng)* Math.PI / 180;
var lat1 = pinLat * Math.PI / 180;
var lat2 = myLat * Math.PI / 180;
var y = Math.sin(dLon) * Math.cos(lat2);
var x = Math.cos(lat1)*Math.sin(lat2) - Math.sin(lat1)*Math.cos(lat2)*Math.cos(dLon);
bearing = Math.atan2(y, x) * 180 / Math.PI;
bearing = bearing + 180;
pin[i]['bearing'] = bearing;
var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
distance = 3958.76 * c;
pin[i]['distance'] = distance;
}
// calculate direction of points and display
function calculateDirection(degree){
var detected = 0;
$("#spot").html("");
for(var i=0;i<pin.length;i++){
if(Math.abs(pin[i].bearing - degree) <= 20){
var away, fontSize, fontColor;
// varry font size based on distance from gps location
if(pin[i].distance>1500){
away = Math.round(pin[i].distance);
fontSize = "16";
fontColor = "#ccc";
} else if(pin[i].distance>500){
away = Math.round(pin[i].distance);
fontSize = "24";
fontColor = "#ddd";
} else {
away = pin[i].distance.toFixed(2);
fontSize = "30";
fontColor = "#eee";
}
$("#spot").append('<div class="name" data-id="'+i+'" style="margin-left:'+(((pin[i].bearing - degree) * 5)+50)+'px;width:'+($(window).width()-100)+'px;font-size:'+fontSize+'px;color:'+fontColor+'">'+pin[i].name+'<div class="distance">'+ away +' miles away</div></div>');
detected = 1;
} else {
if(!detected){
$("#spot").html("");
}
}
}
}
// Start watching the geolocation
function startGeolocation(){
var options = { timeout: 30000 };
watchGeoID = navigator.geolocation.watchPosition(onGeoSuccess, onGeoError, options);
}
// Stop watching the geolocation
function stopGeolocation() {
if (watchGeoID) {
navigator.geolocation.clearWatch(watchGeoID);
watchGeoID = null;
}
}
// onSuccess: Get the current location
function onGeoSuccess(position) {
document.getElementById('geolocation').innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' + 'Longitude: ' + position.coords.longitude;
myLat = position.coords.latitude;
myLng = position.coords.longitude;
if(!dataStatus){
loadData();
}
}
// onError: Failed to get the location
function onGeoError() {
document.getElementById('log').innerHTML += "onError=.";
}
// Start watching the compass
function startCompass() {
var options = { frequency: 100 };
watchCompassID = navigator.compass.watchHeading(onCompassSuccess, onCompassError, options);
}
// Stop watching the compass
function stopCompass() {
if (watchCompassID) {
navigator.compass.clearWatch(watchCompassID);
watchCompassID = null;
}
}
// onSuccess: Get the current heading
function onCompassSuccess(heading) {
var directions = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW', 'N'];
var direction = directions[Math.abs(parseInt((heading.magneticHeading) / 45) + 0)];
document.getElementById('compass').innerHTML = heading.magneticHeading + "<br>" + direction;
document.getElementById('direction').innerHTML = direction;
var degree = heading.magneticHeading;
if($("#arView").is(":visible") && dataStatus != "loading"){
calculateDirection(degree);
}
}
// onError: Failed to get the heading
function onCompassError(compassError) {
document.getElementById('log').innerHTML += "onError=."+compassError.code;
}
// Start checking the accelerometer
function startAccelerometer() {
var options = { frequency: 100 };
watchAccelerometerID = navigator.accelerometer.watchAcceleration(onAccelerometerSuccess, onAccelerometerError, options);
}
// Stop checking the accelerometer
function stopAccelerometer() {
if (watchAccelerometerID) {
navigator.accelerometer.clearWatch(watchAccelerometerID);
watchAccelerometerID = null;
}
}
// onSuccess: Get current accelerometer values
function onAccelerometerSuccess(acceleration) {
// for debug purpose to print out accelerometer values
var element = document.getElementById('accelerometer');
element.innerHTML = 'Acceleration X: ' + acceleration.x + '<br />' +
'Acceleration Y: ' + acceleration.y + '<br />' +
'Acceleration Z: ' + acceleration.z ;
if(acceleration.y > 7){
$("#arView").fadeIn();
$("#topView").hide();
document.getElementById('body').style.background = "#d22";
} else {
$("#arView").hide();
$("#topView").fadeIn();
document.getElementById('body').style.background = "#fff";
}
}
// onError: Failed to get the acceleration
function onAccelerometerError() {
document.getElementById('log').innerHTML += "onError.";
}
</script>
<style>
body {background-color:#fff;font-family:Arial;margin:0;overflow-x:hidden;-webkit-user-select: none;}
.navbar {background-color:#222;height:40px;padding:10px;text-align:center;color:#fff;font-size:20px;font-weight:bold;line-height:40px;}
.navtitle {text-align:center;margin:auto}
.navbtn {background-color:#333;padding:5px 10px;height:30px;color:#fff;font-size:18px;font-weight:bold;line-height:30px;border-radius:4px;border:1px solid #666}
#actionbtn {float:right;}
#viewbtn {float:left;}
.query {padding:10px;background-color:#aaa;border-bottom:1px solid #fff;font-size:14px;font-weight:bold;color:#222;}
.item {padding:20px 10px; background-color:#eee;border-bottom:1px solid #fff;font-size:18px;color:#333;text-shadow:0 1px #fff}
.searchbox {padding:5px;background-color:#eee;border-bottom:1px solid #fff;}
#search {box-sizing: border-box;width:100%;height:40px;font-size:16px;border-radius:20px;border:1px solid #bbb}
.mapView {display:none}
#map {height:200px;}
#arView, #topView {display:none;}
#arView{padding:30px 0; height:70px;text-align:center}
.arMessage {color:#ddd;font-size:14px}
#spot {text-align:center}
.name, .distance {text-shadow:0 1px #666}
.name {padding:15px;font-weight:bold;;background-color:#c22;border-radius:40px;margin-bottom:10px}
#direction {color:#d55;font-size:20px;padding:15px;font-weight:bold;;background-color:#a22;border-radius:40px;display:inline-block;margin-bottom:10px;width:40px;line-height:40px}
.distance {font-size:14px;font-weight:normal;}
#debug {border:1px solid #999;display:none}
.heading {background-color:#999;color:#eee;padding:5px;}
#compass, #accelerometer, #geolocation {padding:5px}
</style>
</head>
<body id="body">
<div id="arView">
<div class="arMessage">↑<br>Tilt down to see all places</div>
<br>
<div class="arMessage">← Move the device around to find spots →</div>
<br>
<div id="direction"></div>
<br>
<div id="spot"></div>
</div>
<div id="topView">
<div class="navbar">
<div id="actionbtn" class="navbtn"> ↵ </div>
<div id="viewbtn" class="navbtn" onclick="toggleView()">Map</div>
<div class="navtitle">Nearby</div>
</div>
<div class="listView">
<div class="listItems"></div>
</div>
<div class="mapView">
<div id="map"></div>
</div>
</div>
<div id="debug">
<div class="heading">Geolocation</div>
<div id="geolocation"></div>
<div class="heading">Compass</div>
<div id="compass"></div>
<div class="heading">Accelerometer</div>
<div id="accelerometer"></div>
<div class="heading">Log</div>
<div id="log"></div>
</div>
</body>
</html>

You are not calling xdkStartAR() and xdkStopAR() in function onAccelerometerSuccess so the camera is not initiating.
Here is the correct onAccelerometerSuccess:
function onAccelerometerSuccess(acceleration) {
// for debug purpose to print out accelerometer values
var element = document.getElementById('accelerometer');
element.innerHTML = 'Acceleration X: ' + acceleration.x + '<br />' +
'Acceleration Y: ' + acceleration.y + '<br />' +
'Acceleration Z: ' + acceleration.z ;
if(acceleration.y > 7){
$("#arView").fadeIn();
$("#topView").hide();
document.getElementById('body').style.background = "#d22";
xdkStartAR();
} else {
$("#arView").hide();
$("#topView").fadeIn();
document.getElementById('body').style.background = "#fff";
xdkStopAR();
}
}
Also I had to include intelxdk.js first and then cordova.js to get it to work in app preview:
<script src="intelxdk.js"></script>
<script src="cordova.js"></script>

Related

How to Align a Google Chart in WebView?

My google chart is not aligned in the center of my android emulator screen. When activity loads up, I get this:
How can I put the chart in the center of the screen? I tried some css, and xml solutions found on stack but they brought no result.
Here is the code I used:
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'ITEM');
data.addColumn('number', 'VALUE');
data.addRows([
[Android.getName(0), Android.getPoint(0)],
[Android.getName(1), Android.getPoint(1)],
[Android.getName(2), Android.getPoint(2)],
[Android.getName(3), Android.getPoint(3)],
[Android.getName(4), Android.getPoint(4)]
]);
// Set chart options
var options = {'title':'You Have a GREAT Music Taste',
pieHole: 0.4,
width: '100%',
height: '750'
};
// Instantiate and draw our chart, passing in some options.
var chart = new
google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'select', selectHandler);
function selectHandler() {
var selection = chart.getSelection();
var message = '';
for (var i = 0; i < selection.length; i++) {
var item = selection[i];
if (item.row != null && item.column != null) {
var str = data.getFormattedValue(item.row, item.column);
message += '{row:' + item.row + ',column:' + item.column + '} = '
+ str + '\n';
} else if (item.row != null) {
var str = data.getFormattedValue(item.row, 0);
message += '{row:' + item.row + ', column:none}; value (col 0) = '
+ str + '\n';
} else if (item.column != null) {
var str = data.getFormattedValue(0, item.column);
message += '{row:none, column:' + item.column + '}; value (row 0)
= ' + str + '\n';
}
}
if (message == '') {
message = 'nothing';
}
Android.sendData('You selected ' + message);
}
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div" style="width:500; height:500"></div>
</body>
</html>

Chrome Android 6x version input value replace duplicate value

This problem happened with my phone (Samsung Galaxy Note 4)
I am using jQuery, I am trying to code such that if a person fill (keyup jquery) value on input, text will spilt into 4 digit number
example : 123412341234 will become 1234-1234-1234
but when i test my code
example : 123412341234
it become
1234-1123-4121-2341-2312-3412-3412-3412-3411-2341-2341-2123-4123-4123-1234-1234-1234
below is my code :
$('#account_bank_number').keyup(function(e){
e.preventDefault();
var account_bank_number = $(this).val();
var account_bank_number_filter = account_bank_number.replace(/-/g, "");
var account_bank_number_new = autoSplit(5, account_bank_number_filter, '-');
$('.debug-mode').html(account_bank_number_new);
}
function autoSplit(number, string, splitChar) {
var stringLength = string.length;
var countNumber = 1;
var newString = '';
for (var i = 0; i <stringLength ; i++) {
if (countNumber == number && string.charAt(i) != splitChar) {
newString = newString+splitChar+string.charAt(i);
countNumber = 2;
continue;
}
newString = newString + string.charAt(i);
countNumber++;
};
return newString;
}
What am I doing wrong?
Hi no sure if you need this but you can do a simple :
var str = "123412341234";
str.replace(/(.{4})/g,"$1-").slice(0,-1);
$(document).ready(function(){
//uncomment if you want do it onload page
//$( "#account_bank_number" ).keyup();
});
//test on click to the input
$( "#account_bank_number" ).click(function() {
$( "#account_bank_number" ).keyup(); //this is a trigger
});
$('#account_bank_number').keyup(function(e){
e.preventDefault();
var account_bank_number = $(this).val();
var account_bank_number_filter = account_bank_number.replace(/-/g, "");//no sure you need it ...
var account_bank_number_new = account_bank_number_filter.replace(/(.{4})/g,"$1-").slice(0,-1);
$('.debug-mode').html(account_bank_number_new);
//adding the value to the input comment if you dont need
this.value = account_bank_number_new;
});
.debug-mode{background-color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<input id="account_bank_number" type="text" value="1234123412341234"/>
<div class="debug-mode"></div>
Simple regex "." is the string. "{4}" is the number to cut the string every 4 characters. "$1-" is the pattern. "$1" is the new string cutting and the "-" at this end is the character being added and the slice is for deleting the last characters added by your replace function. Regards

How to select and swipe left the particular element in the list of items in Mobile app?

//select and swipe the particular element
List<WebElement> instances = driver.findElements(By.className("item-content"));
//I tried this
String instanceName=instances.get(3).getText();
for (WebElement singleInstance : instances) {
String instanceh2Text = singleInstance.getText();
if(instanceh2Text.equals(instanceName)){
Point point = singleInstance.getLocation();
int xcord = point.getX();
System.out.println("Element's Position from left side Is "+xcord +" pixels.");
int ycord = point.getY();
System.out.println("Element's Position from top side Is "+ycord +" pixels.");
//swipe is not worked
JavascriptExecutor jsx = (JavascriptExecutor) driver;
jsx.executeScript("scrollBy(-50,0)");
WebElement startButton=driver.findElement(By.className("button-royal"));
startButton.click();
}
}
//the HTML code
<img ng-class="getRightImage(item)" src="img/Power-Button-icon.png" class="offIcon">
<h2><strong class="ng-binding">aws8 - aws sdk test</strong> <ion-spinner ng-hide="!( item.state == 'stopping' || item.state == 'pending') " style="display:inline" class="spinner spinner-ios ng-hide"> </ion-spinner> </h2>
</div>
<div class="item-options invisible"><ion-option-button class="button-royal icon ion-play button" ng-hide="!( item.state == 'stopped') " ng-click="startInstance(item)"></ion-option-button></div>
//CODE FOR LIST OF ITEMS
<div class="item-content">
<img ng-class="getRightImage(item)" src="img/Power-Button-icon.png" class="offIcon">
<h2><strong class="ng-binding">aws8 - aws sdk test</strong>
<ion-spinner ng-hide="!( item.state == 'stopping' || item.state == 'pending') " style="display:inline" class="spinner spinner-ios ng-hide"> </ion-spinner>
</h2>
</div>
<div class="item-options invisible">
<ion-option-button class="button-royal icon ion-play button" ng-hide="!( item.state == 'stopped') " ng-click="startInstance(item)"></ion-option-button></div>
Well I tried developing a swipe using the WebElement recently, try if this could help you :
/**
* This is a test utility to swipe vertically on the screen using
* Coordinates x,y base being top-left hand corner of element
*
* #param element on the screen to swipe along its width
* #param leftToRight being a boolean flag to point the direction of swipe
*/
public void swipeHorizontally(WebElement element, boolean leftToRight) {
Point elementLocation = element.getLocation();
Dimension elementDimension = element.getSize();
int source_width = elementLocation.getX() + elementDimension.getHeight() / 2;
int source_height = elementLocation.getY() + elementDimension.getWidth() / 2;
int destination_width = source_width;
int destination_height = source_height;
if (leftToRight)
destination_width += elementDimension.getWidth();
else
destination_width -= elementDimension.getWidth();
driver.swipe(source_width, source_height, destination_width, destination_height, 0);
}

How to get nearest location from a list of lat long using google API

I have a list of lat longs using that I need to find nearest one to a position (lat,long).
I do not want to use any formula because it will take lot of time on calculations. Is there any way in which I can use google api or I an upload My list to any google account where I just hit with my current location and it will return with nearest one place and distance?
Yes. first you have to load the geometry library
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script><script>
Then you can use the Google maps function google.maps.geometry.spherical.computeDistanceBetween
You put the results in a for-loop, or in an array; then you return the minimal result.
Here is a web example of your question
<style>
#map {
height: 400px;
}
</style>
<div id="map"></div>
<input type="button" value="Minimal Distance" onclick="displayMinimalDistance()">
<div id="log"></div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script><script>
var myLocations = [
{lat: 50.0,lng: 4.5},
{lat: 50.1,lng: 4.7},
{lat: 50.4,lng: 4.8},
{lat: 50.7,lng: 4.9},
{lat: 50.2,lng: 4.4},
{lat: 50.5,lng: 4.0},
{lat: 50.8,lng: 4.6},
{lat: 50.3,lng: 4.1},
{lat: 50.6,lng: 4.2},
{lat: 50.9,lng: 4.3}
];
var myLocation = {lat: 50.5,lng: 4.5};
// Google maps stuff
function initialize() {
var markers = [];
var myMarker;
var mapCenter = new google.maps.LatLng(50.5, 4.5);
var myOptions = {
zoom: 8,
center: mapCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
addMarkers();
// adding the markers
function addMarkers() {
for(i in myLocations) {
markers.push(new google.maps.Marker({
position: new google.maps.LatLng(myLocations[i].lat, myLocations[i].lng),
title: i,
map: map
})
);
}
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(myLocation.lat, myLocation.lng),
title: 'You are here',
icon: {
url: 'http://www.euroheat.co.uk/images/you-are-here-icon.png',
size: new google.maps.Size(48, 48),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(24,42)
},
map: map
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
// distance stuff
// returns an object: {i: 'key of the location', dist: 'distance'}
function getMinimalDistance(location, locations) {
var minDistance = 20000000; // and now we will look for any shorter distance
var minDistanceKey = -1;
var dist;
for(i in locations) {
dist = getDistance(location, locations[i]);
if(dist < minDistance) {
minDistance = dist;
minDistanceKey = i;
}
}
return {i: minDistanceKey, dist: minDistance};
}
function getDistance(source, destination) {
return google.maps.geometry.spherical.computeDistanceBetween(
new google.maps.LatLng(source.lat, source.lng),
new google.maps.LatLng(destination.lat, destination.lng)
);
}
// writes down the result of getMinimalDistance to a log div
function displayMinimalDistance() {
var minDistance = getMinimalDistance(myLocation, myLocations);
document.getElementById('log').innerHTML =
'Key of the marker at minimal distance: ' + minDistance.i
+ ' - distance: ' + minDistance.dist;
}
</script>
you can also refer this question SQL Distance Query without Trigonometry
there is where i found inspiration for this function
protected void findClosestResources(LatLng mCurrentLocation, GoogleMap map,Context context){
Double currentLatitude=mCurrentLocation.latitude;
Double currentLongitude=mCurrentLocation.longitude;
Double longitudeDifferenceCorrection=1/Math.cos(currentLatitude);
Location=Place.query(LOCATION_TABLE_NAME, M_COLUMNS, "MIN(("+M_COLUMNS[1]+" - "+currentLatitude+") * ("+M_COLUMNS[1]+" - "+currentLatitude+
") + (("+M_COLUMNS[2]+" - "+currentLongitude+") * "+longitudeDifferenceCorrection+
") * (("+M_COLUMNS[2]+" - "+currentLongitude+") * "+longitudeDifferenceCorrection+"))", null,null
, null, null);
if (Location.moveToFirst()) {//select the first row in the cursor object
getInformationAbout(Location);
PlaceMakerOn(map);
Location.close();//close the connection with database
}
this function find the closest location by selecting them from the list of lat lon saved in a SQLite database
using Location=Place.query(LOCATION_TABLE_NAME, M_COLUMNS, "MIN(("+M_COLUMNS[1]+" - "+currentLatitude+") * ("+M_COLUMNS[1]+" - "+currentLatitude+
") + (("+M_COLUMNS[2]+" - "+currentLongitude+") * "+longitudeDifferenceCorrection+
") * (("+M_COLUMNS[2]+" - "+currentLongitude+") * "+longitudeDifferenceCorrection+"))", null,null
, null, null);
where MIN(("+M_COLUMNS[1]+" - "+currentLatitude+") * ("+M_COLUMNS[1]+" - "+currentLatitude+
") + (("+M_COLUMNS[2]+" - "+currentLongitude+") * "+longitudeDifferenceCorrection+
") * (("+M_COLUMNS[2]+" - "+currentLongitude+") * "+longitudeDifferenceCorrection+"))" is the WHERE clausule for the SQLite statement and where M_COLUMNS[1] and M_COLUMNS[2]are the columns in the database for latitude and longitude repectively
by squaring the difference between the latitudes and longitudes of both the locations from the db and the current location the error resulting from this method is reduced while multiplying the squared value of the longitude difference with longitudeDifferenceCorrection does just as the name implies

HTML5 Find nearby geolocation

I am creating an application and I need the app to find the nearest car rentals from the user location or if they input in a postcode. Currently i have looked into previous posts on stack overflow and found the below which finds the users current location. I am new to this so apologies in advance but I am not sure on how I would go from here to make the data display.
<!DOCTYPE html>
<html>
<head>
<title>HTML5 Geolocation</title>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
// Integration with google maps
function loadMap(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
var settings = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), settings);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: 'Your Position!'
});
document.getElementById('status').innerHTML = 'Position Found!';
}
// Initialize geolocation
function initialize() {
if (navigator.geolocation) {
document.getElementById('status').innerHTML = 'Checking...';
navigator.geolocation.getCurrentPosition(
onSuccess,
onError, {
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 120000
});
}
else {
document.getElementById('status').innerHTML = 'Geolocation not supported.';
}
}
// Map position retrieved successfully
function onSuccess(position) {
var data = '';
data += 'latitude: ' + position.coords.latitude + '<br/>';
data += 'longitude: ' + position.coords.longitude + '<br/>';
data += 'altitude: ' + position.coords.altitude + '<br/>';
data += 'accuracy: ' + position.coords.accuracy + '<br/>';
data += 'altitudeAccuracy: ' + position.coords.altitudeAccuracy + '<br/>';
data += 'heading: ' + position.coords.heading + '<br/>';
data += 'speed: ' + position.coords.speed + '<br/>';
document.getElementById('data').innerHTML = data;
loadMap(position.coords.latitude, position.coords.longitude);
}
// Error handler
function onError(err) {
var message;
switch (err.code) {
case 0:
message = 'Unknown error: ' + err.message;
break;
case 1:
message = 'You denied permission to retrieve a position.';
break;
case 2:
message = 'The browser was unable to determine a position: ' + error.message;
break;
case 3:
message = 'The browser timed out before retrieving the position.';
break;
}
document.getElementById('status').innerHTML = message;
}
</script>
</head>
<body onload="initialize()">
<div id="status"></div>
<div id="data"></div>
<div id="map_canvas" style="width: 640px; height: 480px"></div>
</body>
</html>
How would i get the app to display a list of nearest car rentals when the user selects current location or inputs their postcode?
Thank you.
If you are going to be building a database of car rental locations, MongoDB has built-in geolocation / geospatial query capabilities. In a general sense, it sounds like you need to buy or rent a list of the agencies, get that into a database format, then query that database with geo queries in your html.

Categories

Resources