Add draggable marker and get position openlayer - javascript

Here is my code and i want to drag the marker and get the position can any one help me in this? i am using it in phonegap. i am getting the current location using geolocation plugin and plotting that on the openstreet map but having difficulty in moving the marker.
<html>
<body>
<div id="mapdiv"></div>
<script src="http://www.openlayers.org/api/OpenLayers.js"></script>
<script type="text/javascript">
var storage = window.localStorage;
// onSuccess Callback
// This method accepts a Position object, which contains the
// current GPS coordinates
//
var onSuccess = function(position) {
alert('Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude + '\n' +
'Altitude: ' + position.coords.altitude + '\n' +
'Accuracy: ' + position.coords.accuracy + '\n' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
'Heading: ' + position.coords.heading + '\n' +
'Speed: ' + position.coords.speed + '\n' +
'Timestamp: ' + position.timestamp + '\n');
map = new OpenLayers.Map("mapdiv");
map.addLayer(new OpenLayers.Layer.OSM());
var lonLat = new OpenLayers.LonLat( position.coords.longitude,position.coords.latitude)
.transform(
new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
map.getProjectionObject() // to Spherical Mercator Projection
);
var zoom=16;
var markers = new OpenLayers.Layer.Markers( "Markers" );
map.addLayer(markers);
markers.addMarker(new OpenLayers.Marker(lonLat));
map.setCenter (lonLat, zoom);
};
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
</script>
<script>
</script>
</body>
</html>

Related

Cannot use a variable from 1 function into another function

I want to use lat and lng from the getLocation() function in my marker but it wont work.
I added the alert because if that one works everything will.
I tried var lat = ...
I tried world.lat = ...
Something with return values
function getLocation() {
var onSuccess = function (position) {
console.log('Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude + '\n' +
'Altitude: ' + position.coords.altitude + '\n' +
'Accuracy: ' + position.coords.accuracy + '\n' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
'Heading: ' + position.coords.heading + '\n' +
'Speed: ' + position.coords.speed + '\n' +
'Timestamp: ' + position.timestamp + '\n');
lat = position.coords.latitude;
$('.locationLatitude').text(lat);
lng = position.coords.longitude;
$('.locationLongitude').text(lng);
console.log(`latitude: ${lat} longitude: ${lng}`);
};
function onError(error) {
console.log('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
alert(`code: ${error.code}
message: ${error.message}
Please turn on your GPS`);
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
alert(lat, lng);
function meOnMap() {
marker2 = L.marker([lat, lng]).addTo(map).bindPopup('Your Location').openPopup();
}
I expected that the lat and lng values returns their values from in the other function, but they don't.
It looks like you want lat and lng to be in scope when referenced in your meOnMap function. The comments are on the right track, you could declare them as global variables. To do that, just put var lat, lng; at the top of your file.
Or you could add some paramaters to your meOnMap function declaration and call it inside your success callback function, after it does all the processing stuff:
function meOnMap(lat, lng) {
marker2 = L.marker([lat, lng]).addTo(map).bindPopup('Your Location').openPopup();
}
var onSuccess = function (position) {
...
meOnMap(lat,lng);
};
Try to call your getLocation function.
....
getLocation();
alert(lat, lng);

Cordova geolocation plugin doesn't work on android

I'm using cordova ,geolocation plugin for showing latitude and longitude on android. There are plenty of question same as this so I read and tried their solution but couldn't fix the problem. The code below works perfectly on browser.
I tried 3 method, first: "navigator.geolocation.watchPosition" which returns wrong result(37.42,-122.08) in emulator(Android Studio) and doesn't return anything in device.
I also tried "navigator.geolocation.getCurrentPosition" with both "enableHighAccuracy" set 'true' and 'false' and I get timeOut error alerted.
When I delete deviceready, I don't get the timeOut, just wrong result from all three methods.
(function (window) {
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var minAccuracyInMetres = 50;
var positionWatcher;
positionWatcher = navigator.geolocation.watchPosition(
geolocationSuccess2,
geolocationError2,
{ maximumAge: 0, timeout: 100000, enableHighAccuracy: true });
function geolocationSuccess2(position) {
// Reject if accuracy is not sufficient
if (position.coords.accuracy > minAccuracyInMetres) {
return;
}
// Only single position required so clear watcher
navigator.geolocation.clearWatch(positionWatcher);
alert('Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude + '\n' +
'Altitude: ' + position.coords.altitude + '\n' +
'Accuracy: ' + position.coords.accuracy + '\n' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
'Heading: ' + position.coords.heading + '\n' +
'Speed: ' + position.coords.speed + '\n' +
'Timestamp: ' + position.timestamp + '\n');
};
function geolocationError2(error) {
console.warn("Error while retrieving current position. " +
"Error code: " + error.code + ",Message: " + error.message);
}
//2
var onSuccess1 = function (position) {
alert('Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude + '\n' +
'Altitude: ' + position.coords.altitude + '\n' +
'Accuracy: ' + position.coords.accuracy + '\n' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
'Heading: ' + position.coords.heading + '\n' +
'Speed: ' + position.coords.speed + '\n' +
'Timestamp: ' + position.timestamp + '\n');
};
function onError1(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n' + 'highaccuracy: true');
}
var options1 = { maximumAge: 0, timeout: 300000, enableHighAccuracy: true };
navigator.geolocation.getCurrentPosition(onSuccess1, onError1, options1);
//3
var onSuccess = function (position) {
alert('Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude + '\n')
};
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n' + ' high accuracy:false');
}
navigator.geolocation.getCurrentPosition(onSuccess, onError, { enableHighAccuracy: false, timeout: 300 * 1000, maximumAge: 0 });
}
})(window);
I get the watchPosition part from another question in stackoverflow.
I use cordova version: 6.4.0.
I deleted the plugin and tried again but it didn't work.
the device I'm testing with is a lenovo tablet.
Thanks a lot.
UPDATE: my Geolocation version is: 2.4.0 Is it important???
After two days of struggling I turned on "High accuracy" in location settings. The app Works now!!!

How to launch Navigator in cordova in ios

I have an app where (AngularJs+cordova), I need to get current position of the user and navigate to destination using google maps.
I am unable to get it work in iOS:
I have tried:
/* $scope.launchNavigator = function() {
console.log("$scope.launchNavigator...");
var deviceType = (navigator.userAgent.match(/iPad/i))  == "iPad" ? "iPad" : (navigator.userAgent.match(/iPhone/i))  == "iPhone" ? "iPhone" : (navigator.userAgent.match(/Android/i)) == "Android" ? "Android" : (navigator.userAgent.match(/BlackBerry/i)) == "BlackBerry" ? "BlackBerry" : "null";
cordova.plugins.diagnostic.isLocationEnabled(onRequestSuccess, onRequestFailure);
if(deviceType === 'Android'){
cordova.plugins.locationAccuracy.request(onRequestSuccess, onRequestFailure, cordova.plugins.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY);
}
else {
// vm.showGPSAlert = true;
// vm.GPSTextAlert = "Please enable Location Services in Settings and Try again"
//function onDeviceReady() {
cordova.plugins.diagnostic.switchToLocationSettings();
//navigator.geolocation.getCurrentPosition(onSuccess, onError);
//}
}
}
function onRequestSuccess(success){
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
}
function onSuccess(position){
console.log('Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude + '\n' +
'Altitude: ' + position.coords.altitude + '\n' +
'Accuracy: ' + position.coords.accuracy + '\n' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
'Heading: ' + position.coords.heading + '\n' +
'Speed: ' + position.coords.speed + '\n' +
'Timestamp: ' + position.timestamp + '\n');
latitudeStart = position.coords.latitude;
longitudeStart = position.coords.longitude;
launchnavigator.isAppAvailable(launchnavigator.APP.GOOGLE_MAPS, function(isAvailable){
var app;
console.log("Location navigate .lat." + )
if(isAvailable){
app = launchnavigator.APP.GOOGLE_MAPS;
}else{
console.warn("Google Maps not available - falling back to user selection");
app = launchnavigator.APP.USER_SELECT;
}
launchnavigator.navigate([vm.dest.latitude,vm.dest.longitude], {
app: app,
start: [latitudeStart,longitudeStart]
});
});
}
function onError(){
}
function onRequestFailure(error){
console.error("Accuracy request failed: error code="+error.code+"; error message="+error.message);
if(error.code !== cordova.plugins.locationAccuracy.ERROR_USER_DISAGREED){
if(window.confirm("Failed to automatically set Location Mode to 'High Accuracy'. Would you like to switch to the Location Settings page and do this manually?")){
cordova.plugins.diagnostic.switchToLocationSettings();
}
}
}*/
<--the above doesn't work for both iOS and Android-->
For android, following works:
/*Get Direction*/
function onDeviceReady() {
//window.open = cordova.InAppBrowser.open;
console.log("Hello... Device redy");
var latitudeStart = '';
var longitudeStart = '';
$scope.launchNavigator = function() {
function onRequestSuccess(success){
console.log("Successfully requested accuracy: "+success.message);
if(navigator.geolocation){
console.log("navigator.geolocation works well");
}
else{
console.log("navigator.geolocation doesnt works well");
}
console.log("Luanch navigate..");
var onSuccess = function(position) {
console.log('Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude + '\n' +
'Altitude: ' + position.coords.altitude + '\n' +
'Accuracy: ' + position.coords.accuracy + '\n' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
'Heading: ' + position.coords.heading + '\n' +
'Speed: ' + position.coords.speed + '\n' +
'Timestamp: ' + position.timestamp + '\n');
latitudeStart = position.coords.latitude;
longitudeStart = position.coords.longitude;
launchnavigator.isAppAvailable(launchnavigator.APP.GOOGLE_MAPS, function(isAvailable){
var app;
if(isAvailable){
app = launchnavigator.APP.GOOGLE_MAPS;
}else{
console.warn("Google Maps not available - falling back to user selection");
app = launchnavigator.APP.USER_SELECT;
}
launchnavigator.navigate([vm.dest.latitude,vm.dest.longitude], {
app: app,
start: [latitudeStart,longitudeStart]
});
});
};
// onError Callback receives a PositionError object
//
function onError(erro) {
console.log('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
navigator.geolocation.getCurrentPosition(onSuccess, onError,{enableHighAccuracy:true});
}
function onRequestFailure(error){
console.error("Accuracy request failed: error code="+error.code+"; error message="+error.message);
if(error.code !== cordova.plugins.locationAccuracy.ERROR_USER_DISAGREED){
if(window.confirm("Failed to automatically set Location Mode to 'High Accuracy'. Would you like to switch to the Location Settings page and do this manually?")){
cordova.plugins.diagnostic.switchToLocationSettings();
}
}
}
cordova.plugins.locationAccuracy.request(onRequestSuccess, onRequestFailure, cordova.plugins.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY);
}
the above doesn't work for both iOS and Android
Firstly, I would use cordova-plugin-device to determine the platform rather than user agent sniffing - it is more robust.
Secondly, it appears you have a function dependent on the deviceready event which is invoked on the successful outcome of a plugin result:
function onRequestSuccess(success){
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
}
Cordova plugins are dynamically loaded before the deviceready event is invoked, so it's likely that the inner function is never invoked.
Thirdly, the success callback function for both cordova.plugins.diagnostic.isLocationEnabled() and cordova.plugins.locationAccuracy.request() appears to be onRequestSuccess().
Both of the former are invoked in serial synchrony but their callbacks are invoked asynchronously, so this is likely to lead to problems.
I would try something like this:
function onDeviceReady(){
console.log("onDeviceReady...");
$scope.launchNavigator = function() {
console.log("$scope.launchNavigator...");
cordova.plugins.diagnostic.isLocationEnabled(function(enabled){
if(!enabled){
if(device.platform === 'Android'){
cordova.plugins.locationAccuracy.request(getCurrentPosition,
function(error){
console.error("Accuracy request failed: error code="+error.code+"; error message="+error.message);
if(error.code !== cordova.plugins.locationAccuracy.ERROR_USER_DISAGREED){
if(window.confirm("Failed to automatically set Location Mode to 'High Accuracy'. Would you like to switch to the Location Settings page and do this manually?")){
cordova.plugins.diagnostic.switchToLocationSettings();
}
}
}, cordova.plugins.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY);
}
else {
// vm.showGPSAlert = true;
// vm.GPSTextAlert = "Please enable Location Services in Settings and Try again"
//function onDeviceReady() {
cordova.plugins.diagnostic.switchToLocationSettings();
//navigator.geolocation.getCurrentPosition(onSuccess, onError);
//}
}
}else{
getCurrentPosition();
}
}, function onLocationEnabledFailure(error){
console.error("Failed to check if location is enabled");
});
function getCurrentPosition(){
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
function onSuccess(position){
console.log('Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude + '\n' +
'Altitude: ' + position.coords.altitude + '\n' +
'Accuracy: ' + position.coords.accuracy + '\n' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
'Heading: ' + position.coords.heading + '\n' +
'Speed: ' + position.coords.speed + '\n' +
'Timestamp: ' + position.timestamp + '\n');
latitudeStart = position.coords.latitude;
longitudeStart = position.coords.longitude;
launchnavigator.isAppAvailable(launchnavigator.APP.GOOGLE_MAPS, function(isAvailable){
var app;
console.log("Location navigate .lat." + )
if(isAvailable){
app = launchnavigator.APP.GOOGLE_MAPS;
}else{
console.warn("Google Maps not available - falling back to user selection");
app = launchnavigator.APP.USER_SELECT;
}
launchnavigator.navigate([vm.dest.latitude,vm.dest.longitude], {
app: app,
start: [latitudeStart,longitudeStart]
});
});
}
function onError(positionError){
// Handle Error
}
} //$scope.launchNavigator
}// onDeviceReady
In general, I would highly recommend using Safari Remote Debugging and Chrome Remote Debugging tools to debug your app while running on iOS and Android devices respectively.
Using the step-through debugger with appropriate breakpoints will highlight issues such as those present in your code snippet.
See the Debugging Cordova apps section in the Cordova docs for details.

How to use appendTo to display information instead of in an alert box?

I'm a newbie so thanks in advance for any help.
I am setting up a simple geolocation page.
Currently when I click a button, an alert popup box states the geolocation settings.
The problem - instead of the result popping up in a box, I need the geolocation info to display on the page itself.
I was told I need to use the appendTo element and I've tried many different ways but nothing happens.
Here is the current script:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Geolocation</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.
js"</script>
<section>
<script>
$(document).ready(function() {
$('#startGeo').click(checkLocation);
function checkLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getLocation,
locationFail);
}
else {
document.write('You do not have geolocation');
}
}
function getLocation(position) {
var latitude = position.coords.latitute;
var longitude = position.coords.longitude;
var accuracy = position.coords.accuracy;
var timestamp = position.coords.timestamp;
alert('latitude: ' + latitude + 'longitude: ' + longitude +
'accuracy: ' + accuracy + 'timestamp: ' + timestamp);
}
function locationFail() {
document.write('We did not get your location. Please check your
settings.')
}
});
</script>
</head>
<body>
<button id="startGeo">Click here to check your geolocation
abilities</button>
</body>
</html>
Create a container in your html
<div id="geoDisplay"></div>
Then create an element containing the geolocation and append it to the new container.
$('<div>latitude: ' + latitude + ' longitude: ' + longitude +
' accuracy: ' + accuracy + ' timestamp: ' + timestamp + '</div>')
.appendTo($('#geoDisplay'));
Now every time you click the button, it will append a div containing the geolocation information.
Insert a <p class="data"></p> in your document
Replace:
alert('latitude: ' + latitude + 'longitude: ' + longitude +
'accuracy: ' + accuracy + 'timestamp: ' + timestamp);
}
With:
$('.data').html('latitude: ' + latitude + 'longitude: ' + longitude +
'accuracy: ' + accuracy + 'timestamp: ' + timestamp);
}
Here is a simple way of using append, which is very similar to appendTo, just with a different syntax:
$('body').append('latitude: ' + latitude + 'longitude: ' + longitude + 'accuracy: ' + accuracy + 'timestamp: ' + timestamp);
You need to create an element and add it to your DOM. For example:
var coordlabel = '<label>latitude: ' + latitude + 'longitude: ' + longitude +
'accuracy: ' + accuracy + 'timestamp: ' + timestamp + '</label>';
$('body').append(coordlabel);
I assume you are asking how to get your string:
'latitude: ' + latitude + 'longitude: ' + longitude + 'accuracy: ' + accuracy + 'timestamp: ' + timestamp
inside an existing node on the DOM.
If this is the case, then please read the remaining information in this post because there are some things you need to know.
DOM stands for the Document Object Model.
Nodes are your html Elements that can be manipulated by Javascript using selectors. Example. JQUERY: $('#element') is a node selector.
If you are wanting to use Jquery to output your string generated by javascript then you would do:
var str = 'latitude: ' + latitude + 'longitude: ' + longitude + 'accuracy: ' + accuracy + 'timestamp: ' + timestamp;
$('#element').text(str);
http://jsfiddle.net/amLtprmt/
This will not append the Node, i do not believe that is what you were trying to do.
To do this in native JavaScript you would do:
var node = document.getElementById('element');
var str = 'latitude: ' + latitude + 'longitude: ' + longitude + 'accuracy: ' + accuracy + 'timestamp: ' + timestamp;
node.innerHTML = '';
node.appendChild(document.createTextNode(str));
http://jsfiddle.net/56tp7te1/
This is assuming your html looks similar to:
<html>
<body>
<div id='element'></div>
</body>
</html>

Speed Coordinate shows null value in GeoLocation PhoneGap

i am creating android application that gets Lat Lng and check the speed of user i am using PhoneGap GeoLocation Api but i am getting only Longitude and Latitude but in Altitude and Speed it shows null
here is the JavaScript that i get from PhoneGap website
<script type="text/javascript">
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
var options = { enableHighAccuracy: true };
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('time');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'Altitude: ' + position.coords.altitude + '<br />' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '<br />' +
'Speed: ' + position.coords.speed + '<br />' +
'Timestamp: ' + new Date(position.timestamp) + '<br />';
setTimeout('loop();',100);
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
function loop(){
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
</script>
I am check this in Android Mobile as well as emulator same result both places that is null
The Html part is
<body>
<p id="time">Finding geolocation...</p>
Source
it might be device specific, as to whether or not those parameters are supported "If the implementation cannot provide {those variables you're having trouble with} information, the value of this attribute must be null."

Categories