Phone gap geolocation with google maps - android

I wanna make an app which requires me to get my position and display it on google maps. I used the code from http://wiki.phonegap.com/w/page/16494764/PhoneGap%20Geolocation%20Sample%20Application.
I am developing for Android 2.2 using phonegap 2.0.0. I am using the emulator 2.2.
I have installed everything from Phonegap correctly and i obtained a google Api3 key for the map.
I place the key after: http://maps.google.com/maps/api/staticmap?center=(here i place the key). Now when i start the app i use CMD to send coördinates.
Telnet Localhost 5554, geo fix et cetera. When i start the app it will give an error:
Cant retrieve position Error[object PositionError].
I don't get the error anymore (i added enable HighAccuracy).
But it doesnt show anything either. So i think i did something wrong with the google map or i forgot something.
Could anyone help me? It shows a question mark in the top left corner.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta name="viewport" content="width=device-width; height=device-height; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Beer Me</title>
<link rel="stylesheet" href="/master.css" type="text/css" media="screen" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova-2.0.0.js"></script>
<script type="text/javascript">
function loader() {
var state = document.readyState;
if (state == 'loaded' || state == 'complete') {
run();
} else {
if (navigator.userAgent.indexOf('Browzr') > -1) {
setTimeout(run, 250);
} else {
document.addEventListener('deviceready',run,false);
}
}
}
function run() {
var imageUrl = "http://maps.google.com/maps/api/staticmap?sensor=false&center=" + latitude + ',' + longitude +
"&zoom=14&size=300x400&markers=color:blue|label:S|" + latitude + ',' + longitude;
console.log("imageUrl-" + imageUrl);
$("#map").remove();
$(document.body).append(
$(document.createElement("img")).attr("src", imageUrl).attr('id', 'map')
);
var fail = function(e) {
alert('Can\'t retrieve position.\nError: ' + e);
};
navigator.geolocation.getCurrentPosition(imageUrl, fail,{ enableHighAccuracy: true });
}
</script>
</head>

/* enter code here */ function GetCurrentLocation()
{
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var point = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
// Initialize the Google Maps API v3
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: point,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Place a marker
new google.maps.Marker({
position: point,
map: map
});
});
}
else {
alert('W3C Geolocation API is not available');
}
}
Use this code and set sensor = false on
Hope it will help. Remember that it is not static map.

You will need to import the google java script files into your solution
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
Then can use the code below so to show your location...just substitute your latitude and longitude
var imageUrl = "http://maps.google.com/maps/api/staticmap?sensor=false&center=" + latitude + ',' + longitude +
"&zoom=14&size=300x400&markers=color:blue|label:S|" + latitude + ',' + longitude;
console.log("imageUrl-" + imageUrl);
$("#map").remove();
$(document.body).append(
$(document.createElement("img")).attr("src", imageUrl).attr('id', 'map')
);

Related

Cordova 3.3 Android and Google maps, Chromium error

Just I'm trying to have a min example of Google maps working on Cordova Android.
The code works fine on localhost with Chrome and Firefox, but i can't get it work on the device.
Example code:
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>
<script type='text/javascript'>
window.addEventListener('deviceready',function(){
var latitud = xx.xxxxxxx;
var longitud = x.xxxxxxxxxxxxxxxx;
success(latitud,longitud);
},true);
function success(latitud,longitud) {
var coords = new google.maps.LatLng(latitud, longitud);
var options = {
zoom: 15,
center: coords,
mapTypeControl: false,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("prova_maps"), options);
var marker = new google.maps.Marker({
position: coords,
map: map,
title:"You are here!"
});
}
</script>
</head>
<body>
<h1>Google Maps</h1>
<div id='prova_maps' style='height:250px;width:250px;'></div>
</body>
</html>
I have the following error at console that is directly relaunched with that problem, but can't find a solution for that:
https://imageshack.com/i/f3myppp
I have the access tags added in config.xml.
And even try to add
And in index.html
<script type="text/javascript" src="../platform/js/libs/cordova.js"></script>
Try to add this link in the script...tag
google.maps.event.addDomListener(window, 'load', initialize);

Javascript Error "Uncaught Reference Error: google is not defined" on Android PhoneGap

I recently updated the version of PhoneGap/Cordova I was using to the most recent. There is a page in my app that keeps throwing the following error every time it loads.
Uncaught Reference Error: google is not defined
I tried to use a sample webpage directly from the google developer's site to try and narrow down my options, and still got the same error when trying to load that page on my phone. (found here: https://developers.google.com/maps/documentation/javascript/examples/map-simple). I should note, when running this webpage from google as an .HTML file in Chrome on my desktop it worked fine.
I have also tried to use the solution found here: Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX
however the initialize method was never even called, which leads me to believe it's a problem with my script tag that I'm still missing.
As far as I can tell, I am using proper script calls in my HTML:
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?<KEY>&sensor=false"></script>
and the javascript code that is crashing is as follows:
origins[0] = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
The full code is here:
<!DOCTYPE HTML>
<html>
<head>
<title>MASH Locations</title>
<meta name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
<link rel="stylesheet" type="text/css" href="styles/layout.css" />
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=(myAppKey)&sensor=false"></script>
<script type="text/javascript" charset="utf-8" src="Util.js"></script>
<script type="text/javascript" charset="utf-8" src="QuickSort.js"></script>
<script type="text/javascript" charset="utf-8" src="Location.js"></script>
<script type="text/javascript">
var origins, destinations;
var BORDER_ROW = '<tr><td colspan="3" class="location-result-border"> </td></tr>';
var RESULT_FORMAT = '<tr><td id="result_{7}" class="location-result-row" onclick="onLocationResultClick(\'{0}\', \'{1}\', \'{2}\', \'{3}\', \'{4}\', \'http://cloud.intelligentbits.net/mash/images/{5}\', \'{6}\')">'
+ '<table class="{8}">'
+ '<tr><td class="location-result-distance" rowspan="3"><div>{9}</div>miles</td>'
+ '<td class="location-result-logo" rowspan="3"><img src="http://sqldb.intelligentbits.net/mash/images/{5}" alt="{0}" /></td>'
+ '<td class="location-result-name">{0}</td></tr>'
+ '<tr><td class="location-result-address">{10}</td></tr>'
+ '<tr><td class="location-result-city">{11}</td></tr></table></td></tr>';
function onLoad()
{
// Wait for PhoneGap to load
document.addEventListener("deviceready", onDeviceReady, false);
}
// PhoneGap is ready
function onDeviceReady()
{
navigator.geolocation.getCurrentPosition(onPositionFound, onPositionError);
}
function onPositionFound(position)
{
// get the current location
origins = new Array();
origins[0] = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
document.getElementById('finding').innerText = 'Finding our locations...';
readFile('http://sqldb.intelligentbits.net/mash/locations.txt', onLocationsFound);
}
// onPositionError Callback receives a PositionError object
function onPositionError(error)
{
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
function onLocationsFound(text)
{
if (text == null || text.length == 0)
{
document.getElementById('finding').innerText = 'An error occurred.';
return;
}
// split the text into lines (one line per location)
var lines = text.split(/\r?\n/g);
if (lines.length == 0)
{
document.getElementById('finding').innerText = 'An error occurred.';
return;
}
// destinations
destinations = new Array();
var locIdx = 0;
// iterate over lines/locations
for (var i = 0; i < lines.length; ++i)
{
// split into fields
var loc = new Location();
var fields = lines[i].split(';');
for (var j = 0; j < fields.length; ++j)
{
// split fields into name and value
var tokens = fields[j].split('=');
if (tokens.length != 2) continue;
switch (tokens[0].toUpperCase())
{
case 'NAME':
loc.Name = tokens[1];
break;
case 'ADDRESS':
loc.StreetAddress = tokens[1];
break;
case 'CITY':
loc.City = tokens[1];
break;
case 'STATE':
loc.Region = tokens[1];
break;
case 'POSTAL':
loc.PostalCode = tokens[1];
break;
case 'PHONE':
loc.Phone = tokens[1];
break;
case 'HOURS':
loc.Hours = tokens[1];
break;
case 'LOGO':
loc.LogoFileName = tokens[1];
break;
case 'EMAIL':
loc.Email = tokens[1];
break;
}
}
// save the destination
destinations[locIdx++] = loc;
}
if (destinations.length == 0)
document.getElementById('finding').innerText = 'An error occurred.';
else
calculateDistances(origins, destinations);
}
function calculateDistances(orig, dest) {
// the passed-in destinations are arrays of Location objects; Google Maps wants strings
var destStrings = new Array();
for (var i = 0; i < dest.length; ++i)
destStrings[i] = dest[i].ToAddressString();
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: orig,
destinations: destStrings,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, onDistancesFound);
}
function onDistancesFound(response, status)
{
if (status != google.maps.DistanceMatrixStatus.OK)
{
alert('Error was: ' + status);
}
else
{
// get the place we'll store the list
var p = document.getElementById('finding');
var table = document.getElementById('location-results');
var orig = response.originAddresses;
var dest = response.destinationAddresses;
p.innerText = 'Tap a location for more options.';
// iterate over origins
for (var i = 0; i < orig.length; ++i) {
var results = response.rows[i].elements;
// iterate over destinations
for (var j = 0; j < results.length; ++j) {
// split the location into the amount and units
var distance = results[j].distance.text.Trim().split(' ');
// update the locations
destinations[j].DistanceFromUser = parseFloat(distance[0]);
destinations[j].DistanceUnits = distance[1];
destinations[j].TimeFromUser = results[j].duration.text;
}
}
// sort the distances
QuickSort(destinations, 'DistanceFromUser');
// print the results
var tablerows = '';
for (var i = 0; i < destinations.length; ++i) {
var loc = destinations[i];
tablerows += RESULT_FORMAT.Format(loc.Name, loc.Phone, loc.ToAddressString(), loc.ToTwoLineAddressString(),
loc.Hours, loc.LogoFileName, loc.Email, i, 'location-result-' + ((i + 1) % 2 == 0 ? 'even' : 'odd'),
loc.DistanceFromUser, loc.StreetAddress, loc.City);
}
tablerows += '<tr><td><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/></td></tr>';
// append the rows
table.innerHTML += tablerows;
}
}
function onLocationResultClick(name, phone, address, displayAddress, hours, imageUrl, email)
{
// save the name and address to local storage for the directions
window.localStorage.setItem('location-position', address);
window.localStorage.setItem('location-address', displayAddress);
window.localStorage.setItem('location-title', name);
window.localStorage.setItem('location-hours', hours);
window.localStorage.setItem('location-phone', phone);
window.localStorage.setItem('location-imageUrl', imageUrl);
window.localStorage.setItem('location-contact', email);
// call link
window.location = 'location.html';
}
</script>
</head>
<body onload="onLoad()">
<h1>
<a href="index.html" class="back">
<div>
<span></span>
</div> <span class="text">Back</span>
</a> Nearest Locations
</h1>
<div id="location-results-wrapper">
<h1 style="position: static; width: 94%;">
<a href="#" class="back">
<div>
<span></span>
</div> <span class="text">Back</span>
</a> #
</h1>
<table id="location-results">
<tr>
<td id="finding" style="vertical-align: top;">Finding your
location...</td>
<tr>
</table>
</div>
</body>
</html>
and the exact error log:
06-27 09:06:00.624: E/Web Console(15020): Uncaught ReferenceError: google is not defined at file:///android_asset/www/locations.html:41
Try these
Check your internet connection
Keep Map API script tag as a first script tag in your code.
i.e Before loading any other javascripts load map API.
Hope this helps.
I found my solution. When running the update command for PhoneGap, the cordova.js and config.xml files were not copied over into the my project. I'm not sure if this is intentional (I easily could have missed documentation on this somewhere), but it seemed unintuitive at the time. After manually copying these two files into my project, everything worked.
When u're using multiple HTML pages. use the google API javascript on the main page(index). the Ajax will not relaod the map when its refreshed.
If google map api is not defined then it too can cause the problem.
Since i missed out while getting the address from latitude and longitude.

Google Maps API v3 in PhoneGap: Circle duplicating and drawing tangent line after move

(This is a split off from my other post I made, Google Maps API v3 in PhoneGap: markers not drawing properly after move) . I've been working on a Google Maps API 3 application on Android using PhoneGap. It should track the users location and mark the location with a marker and a circle around it. I had been developing this on Android 2.3 and it was working fine. I then upgraded to a phone with Android 4.x and it was still working well, I thought.
Then last week I began noticing Google Maps doing some strange things when I moved the Marker and Circle. It would seem to create a duplicate Marker and Circle instead of just moving them. In the other post, I got an answer for the Marker issue, but not for the Circle. Sometimes if I change zoom then the duplicate Circle seems to go away. But also, it occasionally draws some weird tangent line from the top. See images below.
I started noticing this shortly after I received an Android update on my phone to version 4.1.1. Not sure if that's related, I can't find any info about a problem.
I reduced the map and phonegap code to a pretty minimal sample and its still doing it. I'm pretty sure it isn't related to phonegap. I upgraded my phonegap to 2.2 anyway to be sure, but as expected it didn't help. Can anyone tell if I am doing something wrong when moving the circle?
One solution that I tried was to hide the circle before moving it and then show it again after I move it. That seemed to solve the duplicate and tangent issue, but it made the map flash, which is really annoying when you move it every 3 seconds or so. So that doesn't seem like an acceptable solution. Test code is below. Note that I removed my Google Maps API key in test code.
I've also learned that one way to get it to redraw correctly is to drag the map so that no part of any circle is visible. Then when I drag it back so that the circle is visible, it is redrawn as just one correct circle.
Thanks, Eric
<!DOCTYPE HTML>
<html>
<head>
<title>Marker Test</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html {height: 100%}
body {height: 100%; margin:0; padding:0}
#map_canvas {height: 100%}
</style>
<script type="text/javascript" charset="utf-8" src="js/phonegap.js"></script>
<script type="text/javascript" charset="utf-8" src="http://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE&sensor=true"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// globals
var watchID = null;
var map = null;
var myLocationMarker = null;
var searchCircle = null;
// PhoneGap is ready
//
function onDeviceReady() {
startGPS();
}
function onUnLoad() {
console.log("clearing watch " + watchID);
navigator.geolocation.clearWatch(watchID);
}
function startGPS() {
console.log("In startGPS");
var refreshMilliseconds = 5000;
var options = { frequency: refreshMilliseconds, enableHighAccuracy: true};
watchID = navigator.geolocation.watchPosition(onGPSSuccess, onGPSError, options);
// create Google map
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
myLocationMarker = new google.maps.Marker({
title: 'This is me!',
zIndex: 90,
optimized: false,
map:map
});
searchCircle = new google.maps.Circle({
fillColor: '#c0e4dd',
strokeColor: '#f15f22',
fillOpacity: 0.5,
radius: 1500,
map:map
});
}
var onGPSSuccess = function(p) {
// get the new coordinates
var lat = p.coords.latitude;
var lng = p.coords.longitude;
console.log("watch ID " + watchID);
// now that we have the coordinates, we can move the marker and circle on the Google Map
MoveMarkerAndCircle(lat, lng);
};
var MoveMarkerAndCircle = function(lat, lng) {
var myLocation = new google.maps.LatLng(lat, lng);
myLocationMarker.setPosition(myLocation);
// searchCircle.setVisible(false);
searchCircle.setCenter(myLocation);
// searchCircle.setVisible(true);
map.setCenter(myLocation);
}
var onGPSError = function() {
console.log("GPS Error");
};
var GenerateFakeMovement = function() {
var currentPosition = myLocationMarker.getPosition();
var newLat = currentPosition.lat() + 0.01;
var newLng = currentPosition.lng() + 0.01;
MoveMarkerAndCircle(newLat, newLng);
}
</script>
</head>
<body style="height:100%;text-align:center" onunload="onUnLoad()">
<div id="map_canvas" style="width: 100%;height:80%"></div>
MAKE FAKE MOVEMENT
</body>
</html>
<!DOCTYPE HTML>
<html>
<head>
<title>Marker Test</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html {height: 100%}
body {height: 100%; margin:0; padding:0}
#map_canvas {height: 100%}
</style>
<script type="text/javascript" charset="utf-8" src="http://maps.googleapis.com/maps/api/js?v=3&sensor=true"></script>
<script type="text/javascript" charset="utf-8">
var watchID = null;
var map = null;
var myLocationMarker = null;
var searchCircle = null;
function onDeviceReady() {
startGPS();
}
function onUnLoad() {
console.log("clearing watch " + watchID);
navigator.geolocation.clearWatch(watchID);
}
function startGPS() {
console.log("In startGPS");
var refreshMilliseconds = 5000;
var options = { frequency: refreshMilliseconds, enableHighAccuracy: true};
if(watchID ==null)
watchID = navigator.geolocation.watchPosition(onGPSSuccess, onGPSError, options);
// create Google map
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
myLocationMarker = new google.maps.Marker({
title: 'This is me!',
zIndex: 90,
optimized: false,
map:map
});
searchCircle = new google.maps.Circle({
fillColor: '#c0e4dd',
strokeColor: '#f15f22',
fillOpacity: 0.5,
radius: 1500,
map:map
});
}
var onGPSSuccess = function(p) {
// get the new coordinates
var lat = p.coords.latitude;
var lng = p.coords.longitude;
console.log("watch ID " + watchID);
// now that we have the coordinates, we can move the marker and circle on the Google Map
MoveMarkerAndCircle(lat, lng);
};
var MoveMarkerAndCircle = function(lat, lng) {
var myLocation = new google.maps.LatLng(lat, lng);
myLocationMarker.setPosition(myLocation);
// searchCircle.setVisible(false);
searchCircle.setCenter(myLocation);
// searchCircle.setVisible(true);
map.setCenter(myLocation);
}
var onGPSError = function() {
console.log("GPS Error");
};
function GenerateFakeMovement() {
var currentPosition = myLocationMarker.getPosition();
var newLat = currentPosition.lat() + 0.01;
var newLng = currentPosition.lng() + 0.01;
MoveMarkerAndCircle(newLat, newLng);
}
</script>
</head>
<body style="height:100%;text-align:center" onload="onDeviceReady()" onunload="onUnLoad()">
<div id="map_canvas" style="width: 100%;height:80%"></div>
MAKE FAKE MOVEMENT
</body>
</html>​
May not be entirely related to your problem, but if you bind a circle to a marker you don't have to set the circle position manually.
if (myMarker == undefined) {
myMarker = new google.maps.Marker({
position: mouseEvent.latLng,
title: 'My Position',
map: map,
draggable: true
});
var circle = new google.maps.Circle({
map: map,
radius: 100000, // 100 km
fillOpacity: 0.1,
strokeOpacity: 0.5,
strokeWeight: 1
});
circle.bindTo('center', myMarker, 'position'); //This will set the circle bound to the marker at center
}
So you only need to update the position of the marker.
Hope this helps.
I hope that I'm doing the right thing by posting this as an "answer". I still have the issue, but I have narrowed my own example down to the point that it seems clear it is an issue with Google Maps API v3 on Android 4.1.1 only. The code for the narrowed down test case is below and no longer involves PhoneGap.
I've posted the test page online here:
http://kcwebprogrammers.com/MarkerTest-NoGps.html
If you browse there in Windows (Chrome or IE) or with the Internet browser on Android 2.3, then moving the circle works just fine. If you browse to the same page with the Internet browser on Android 4.1.1, then you'll see that the original circle is still visible after the circle is moved, causing two circles. So I've posted the issue to the Google Maps issue list.
Thanks for the suggestions above. Please let me know if anyone thinks I should do anything different with this post.
<!DOCTYPE HTML>
<html>
<head>
<title>Marker Test</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html {height: 100%}
body {height: 100%; margin:0; padding:0}
#map_canvas {height: 100%}
</style>
<script type="text/javascript" charset="utf-8" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDTGR9VjM2t5ixumkk_jHg155s0C1S5g3Y&sensor=true"></script>
<script type="text/javascript" charset="utf-8">
// globals
var watchID = null;
var map = null;
var myLocationMarker = null;
var searchCircle = null;
var myLocation = null;
function onLoad() {
startGPS();
}
function onUnLoad() {
console.log("clearing watch " + watchID);
}
function startGPS() {
// simulate getting position from GPS
myLocation = new google.maps.LatLng(39, -90);
// create Google map
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center:myLocation
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
google.maps.event.trigger(map, 'resize');
myLocationMarker = new google.maps.Marker({
title: 'This is me!',
zIndex: 90,
optimized: false,
map:map,
position: myLocation
});
searchCircle = new google.maps.Circle({
fillColor: '#c0e4dd',
strokeColor: '#f15f22',
fillOpacity: 0.5,
radius: 1500,
map:map,
center:myLocation
});
// using bindTo instead does not fix the problem
// searchCircle.bindTo('center', myLocationMarker, 'position'); //This will set the circle bound to the marker at center
}
var MoveMarkerAndCircle = function(lat, lng) {
myLocation = new google.maps.LatLng(lat, lng);
myLocationMarker.setPosition(myLocation);
// set circle invisible before moving and visible after does fix redraw for 4.1.1
// but causes some annoying flashing of the circle for 4.1.1 and everything else
// searchCircle.setVisible(false);
searchCircle.setCenter(myLocation);
// searchCircle.setVisible(true);
}
var GenerateFakeMovement = function() {
var currentPosition = myLocationMarker.getPosition();
var newLat = currentPosition.lat() + 0.001;
var newLng = currentPosition.lng() + 0.001;
MoveMarkerAndCircle(newLat, newLng);
}
</script>
</head>
<body style="height:100%;text-align:center" onunload="onUnLoad()" onload="startGPS()">
<div id="map_canvas" style="width: 100%;height:90%"></div>
MOVE MARKER AND CIRCLE
</body>
</html>

Localstorage my geolocation

I want to make an app which gets my coördinates and shows them in google maps (using phonegap and testing on emulator 2.2). Then stores those coördinates in localstorage. I have never used localstorage before so i am not sure on how to do this. I got the geolocation part working. If anyone could adjust my code or show a tutorial which explains how to save the lat/long that i will retreive as i don't have a lot of experience using web-langauges. It would be greatly appreciated.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta name="viewport" content="width=device-width; height=device-height; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Beer Me</title>
<link rel="stylesheet" href="/master.css" type="text/css" media="screen" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" charset="utf-8" src="cordova-2.0.0.js"></script>
<script type="text/javascript">
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
}
//GEOLOCATION
var onSuccess = function(position) {
var myLat = position.coords.latitude;
var myLong = position.coords.longitude;
//MAP
var mapOptions = {
center: new google.maps.LatLng(myLat, myLong),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(myLat, myLong),
map: map,
title:"Hello World!"
});
};
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
navigator.geolocation.getCurrentPosition(onSuccess, onError,{'enableHighAccuracy':true,'timeout':10000});
</script>
</head>
<body onload="onLoad()">
<div id="map_canvas" style="width:400px; height: 400px;">
</div>
</body>
</html>
I would suggest you use the SQLite Databases from Android.
You can then store the locations with two fields and access the data with SQL queries.
A nice tutorial is the one from Lars Vogel.
You could also use the Internal Storage from Android. Using a simple file is easy but not as powerful as the sql variant. When the data size increases reading and storing to the file becomes more cumbersome.

Phonegap storing Coördinates

I am using Cordova 2.0.0 and i am testing on Android 2.2.
So after 2 threads and alot of searching i am finally able get get my geolocation and have it shown in google maps. Now every time i open the app it will get my geolocation and show it in google maps with a marker. Now i want the program to store the data. This is the first time i use html5,JS. When i made a native app i just used the SQLite database.
How would i go on about storing the data?
This is what i have so far, any help tutorials, samples, help and advice would be greatly appreciated.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta name="viewport" content="width=device-width; height=device-height; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Beer Me</title>
<link rel="stylesheet" href="/master.css" type="text/css" media="screen" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" charset="utf-8" src="cordova-2.0.0.js"></script>
<script type="text/javascript">
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess, onError,{'enableHighAccuracy':true,'timeout':10000});
}
//GEOLOCATION
var onSuccess = function(position) {
alert('Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude + '\n');
var myLat = position.coords.latitude;
var myLong = position.coords.longitude;
//MAP
var mapOptions = {
center: new google.maps.LatLng(myLat, myLong),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
};
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
</script>
</head>
<body onload="onLoad()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
You can use a simple SQLite database as usual: http://docs.phonegap.com/en/2.0.0/cordova_storage_storage.md.html#Storage

Categories

Resources