commit eacb95c18a21f14e950cfef86deae5835b5c9b82 Author: zhongjin Date: Sat Sep 22 10:44:38 2018 +0800 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b256deb --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +/.idea/ +/node_modules +/_socket +/.build +/lib/js +/lib/css +/www/_socket +/cordova/www +/cordova/platforms/android/assets/www +/cordova/platforms/android/.gradle +/cordova/platforms/android/build +/www +/platforms/android/assets/www +!/platforms/android/assets/www/index.html +/platforms/android/.gradle +/platforms/android/*.keystore +/platforms/android/assets/www/cordova-js-src +/platforms/android/assets/www/css +/platforms/android/assets/www/icon +/platforms/android/assets/www/img +/platforms/android/assets/www/js +/platforms/android/assets/www/lib +/platforms/android/assets/www/plugins +/platforms/android/assets/www/widgets +/platforms/android/assets/www/cordova.js +/platforms/android/assets/www/cordova_plugins.js +/platforms/android/assets/www/signals +/platforms/android/cordova/node_modules +/platforms/android/CordovaLib/build diff --git a/Gruntfile.js b/Gruntfile.js new file mode 100644 index 0000000..fac63ed --- /dev/null +++ b/Gruntfile.js @@ -0,0 +1,363 @@ +// To use this file in WebStorm, right click on the file name in the Project Panel (normally left) and select "Open Grunt Console" + +/** @namespace __dirname */ +/* jshint -W097 */ +/* jshint strict:false */ +/* jslint node: true */ +'use strict'; + +// ## How to build +// +// Copy real file with keys yunkong2.vis.keystore to yunkong2.vis.cordova\platforms\android +// ``` +// npm install +// grunt release +// or +// grunt build +// ``` +// +// **Note**: if "grunt" command not found, install grunt-cli with "npm i grunt-cli -g" +// +// +// Output is in ```yunkong2.vis.cordova\platforms\android\build\outputs\apk``` +// +// To test it on android Handy: +// ``` +// cordova run android +// ``` + +// How to create release: +// extend platforms/android/release-signing.properties with +// keyPassword=xxx +// storePassword=xxx +// +// Copy img/icon.png into www/icon/ +// Copy yunkong2.vis.keystore into platforms/android/ and +// run "grunt release" + + +module.exports = function (grunt) { + + var srcDir = __dirname + '/'; + var pkg = grunt.file.readJSON('package.json'); + var version = pkg.version; + var fs = require('fs'); + + // Project configuration. + grunt.initConfig({ + pkg: pkg, + clean: { + all: ['www/**/*'] + }, + replace: { + core: { + options: { + patterns: [ + { + match: /var version = *'[\.0-9]*';/g, + replacement: "var version = '" + version + "';" + }, + { + match: /version="[\.0-9]*"/g, + replacement: 'version="' + version + '"' + }, + { + match: /"version": *"[\.0-9]*",/g, + replacement: '"version": "' + version + '",' + }, + { + match: /version: *"[\.0-9]*",/, + replacement: 'version: "' + version + '",' + }, + { + match: /version: *'[\.0-9]*',/, + replacement: "version: '" + version + "'," + }, { + match: //, + replacement: '' + }, + { + match: /# yunkong2\.vis Version [\.0-9]+/, + replacement: '# yunkong2.vis Version ' + version + }, + { + match: /# yunkong2\.flot version = *'[\.0-9]*';/g, + replacement: "yunkong2.flot version = '" + version + "';" + }, + { + match: /# yunkong2\.rickshaw version = *'[\.0-9]*';/g, + replacement: "yunkong2.rickshaw version = '" + version + "';" + }, + { + match: /# dev build [\.0-9]+/g, + replacement: '# dev build 0' + } + ] + }, + files: [ + { + expand: true, + flatten: true, + src: [ + srcDir + 'config.xml', + srcDir + 'package.json', + srcDir + 'io-package.json' + ], + dest: srcDir + } + ] + }, + index: { + options: { + patterns: [ + { + match: /\.\.\/\.\.\//g, + replacement: '' + }, + { + match: / + + + + diff --git a/plugins/cordova-plugin-fullscreen/package.json b/plugins/cordova-plugin-fullscreen/package.json new file mode 100644 index 0000000..3939e80 --- /dev/null +++ b/plugins/cordova-plugin-fullscreen/package.json @@ -0,0 +1,101 @@ +{ + "_args": [ + [ + { + "raw": "cordova-plugin-fullscreen", + "scope": null, + "escapedName": "cordova-plugin-fullscreen", + "name": "cordova-plugin-fullscreen", + "rawSpec": "", + "spec": "latest", + "type": "tag" + }, + "D:\\pWork\\yunkong2.vis.cordova\\node_modules" + ] + ], + "_from": "cordova-plugin-fullscreen@latest", + "_id": "cordova-plugin-fullscreen@1.2.0", + "_inCache": true, + "_location": "/cordova-plugin-fullscreen", + "_nodeVersion": "6.11.2", + "_npmOperationalInternal": { + "host": "s3://npm-registry-packages", + "tmp": "tmp/cordova-plugin-fullscreen-1.2.0.tgz_1502480881540_0.3836044427007437" + }, + "_npmUser": { + "name": "mesmotronic", + "email": "npm.support@mesmotronic.com" + }, + "_npmVersion": "5.3.0", + "_phantomChildren": {}, + "_requested": { + "raw": "cordova-plugin-fullscreen", + "scope": null, + "escapedName": "cordova-plugin-fullscreen", + "name": "cordova-plugin-fullscreen", + "rawSpec": "", + "spec": "latest", + "type": "tag" + }, + "_requiredBy": [ + "#USER" + ], + "_resolved": "https://registry.npmjs.org/cordova-plugin-fullscreen/-/cordova-plugin-fullscreen-1.2.0.tgz", + "_shasum": "482b38e881715e1fc812d6c35bea1072efb424a7", + "_shrinkwrap": null, + "_spec": "cordova-plugin-fullscreen", + "_where": "D:\\pWork\\yunkong2.vis.cordova\\node_modules", + "author": { + "name": "Neil Rackett" + }, + "bugs": { + "url": "https://github.com/mesmotronic/cordova-fullscreen-plugin/issues" + }, + "cordova": { + "id": "cordova-plugin-fullscreen", + "platforms": [ + "android" + ] + }, + "dependencies": {}, + "description": "Plugin for Cordova (or PhoneGap) 3.0+ to enable true full screen on Android devices using lean and immersive modes", + "devDependencies": {}, + "directories": {}, + "dist": { + "integrity": "sha512-cl8mE1MoTjv4JlwV6dw3nOc7Qj18WuNJLf2jHWUmRTYzCI/SW9ym/ghSVvonTVnaoECuHrOpmAfUoFzbb8kf2Q==", + "shasum": "482b38e881715e1fc812d6c35bea1072efb424a7", + "tarball": "https://registry.npmjs.org/cordova-plugin-fullscreen/-/cordova-plugin-fullscreen-1.2.0.tgz" + }, + "engines": [ + { + "name": "cordova", + "version": ">=3.0.0" + } + ], + "gitHead": "c17032965a56c59ae9d4f5fdbccd85406ebec605", + "homepage": "https://github.com/mesmotronic/cordova-fullscreen-plugin#readme", + "keywords": [ + "cordova", + "android", + "fullscreen", + "lean", + "immersive", + "ecosystem:cordova", + "cordova-android" + ], + "license": "BSD", + "maintainers": [ + { + "name": "mesmotronic", + "email": "npm.support@mesmotronic.com" + } + ], + "name": "cordova-plugin-fullscreen", + "optionalDependencies": {}, + "readme": "ERROR: No README data found!", + "repository": { + "type": "git", + "url": "git+https://github.com/mesmotronic/cordova-fullscreen-plugin.git" + }, + "version": "1.2.0" +} diff --git a/plugins/cordova-plugin-fullscreen/plugin.xml b/plugins/cordova-plugin-fullscreen/plugin.xml new file mode 100644 index 0000000..466a326 --- /dev/null +++ b/plugins/cordova-plugin-fullscreen/plugin.xml @@ -0,0 +1,74 @@ + + + + + + + cordova-plugin-fullscreen + Plugin for Cordova (or PhoneGap) 3.0+ to enable true full screen on Android devices using lean and immersive modes + cordova,android,fullscreen,lean,immersive,statusbar + https://github.com/mesmotronic/cordova-fullscreen-plugin.git + + BSD + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/cordova-plugin-fullscreen/src/android/com/mesmotronic/plugins/FullScreenPlugin.java b/plugins/cordova-plugin-fullscreen/src/android/com/mesmotronic/plugins/FullScreenPlugin.java new file mode 100644 index 0000000..976f2ac --- /dev/null +++ b/plugins/cordova-plugin-fullscreen/src/android/com/mesmotronic/plugins/FullScreenPlugin.java @@ -0,0 +1,503 @@ +package com.mesmotronic.plugins; + +import org.apache.cordova.CallbackContext; +import org.apache.cordova.CordovaPlugin; +import org.apache.cordova.PluginResult; +import org.apache.cordova.CordovaInterface; +import org.apache.cordova.CordovaWebView; +import org.json.JSONArray; +import org.json.JSONException; + +import android.app.Activity; +import android.graphics.Point; +import android.os.Build; +import android.view.View; +import android.view.Window; +import android.view.WindowManager; +import android.graphics.Color; +import android.os.Handler; + +public class FullScreenPlugin extends CordovaPlugin +{ + public static final String ACTION_IS_SUPPORTED = "isSupported"; + public static final String ACTION_IS_IMMERSIVE_MODE_SUPPORTED = "isImmersiveModeSupported"; + public static final String ACTION_IMMERSIVE_WIDTH = "immersiveWidth"; + public static final String ACTION_IMMERSIVE_HEIGHT = "immersiveHeight"; + public static final String ACTION_LEAN_MODE = "leanMode"; + public static final String ACTION_SHOW_SYSTEM_UI = "showSystemUI"; + public static final String ACTION_SHOW_UNDER_STATUS_BAR = "showUnderStatusBar"; + public static final String ACTION_SHOW_UNDER_SYSTEM_UI = "showUnderSystemUI"; + public static final String ACTION_IMMERSIVE_MODE = "immersiveMode"; + public static final String ACTION_SET_SYSTEM_UI_VISIBILITY = "setSystemUiVisibility"; + + private CallbackContext context; + private Activity activity; + private Window window; + private View decorView; + private int mLastSystemUIVisibility = 0; + private final Handler mLeanBackHandler = new Handler(); + private final Runnable mEnterLeanback = new Runnable() { + @Override + public void run() { + leanMode(); + } + }; + + /** + * Sets the context of the Command. This can then be used to do things like + * get file paths associated with the Activity. + * + * @param cordova The context of the main Activity. + * @param webView The CordovaWebView Cordova is running in. + */ + @Override + public void initialize(final CordovaInterface cordova, final CordovaWebView webView) { + super.initialize(cordova, webView); + + this.cordova.getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + // Clear flag FLAG_FORCE_NOT_FULLSCREEN which is set initially + // by the Cordova. + Window window = cordova.getActivity().getWindow(); + window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); + + // Read 'StatusBarBackgroundColor' from config.xml, default is #000000. + setStatusBarBackgroundColor(preferences.getString("StatusBarBackgroundColor", "#000000")); + } + }); + } + + @Override + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException + { + context = callbackContext; + activity = cordova.getActivity(); + window = activity.getWindow(); + decorView = window.getDecorView(); + + if (ACTION_IS_SUPPORTED.equals(action)) + return isSupported(); + else if (ACTION_IS_IMMERSIVE_MODE_SUPPORTED.equals(action)) + return isImmersiveModeSupported(); + else if (ACTION_IMMERSIVE_WIDTH.equals(action)) + return immersiveWidth(); + else if (ACTION_IMMERSIVE_HEIGHT.equals(action)) + return immersiveHeight(); + else if (ACTION_LEAN_MODE.equals(action)) + return leanMode(); + else if (ACTION_SHOW_SYSTEM_UI.equals(action)) + return showSystemUI(); + else if (ACTION_SHOW_UNDER_STATUS_BAR.equals(action)) + return showUnderStatusBar(); + else if (ACTION_SHOW_UNDER_SYSTEM_UI.equals(action)) + return showUnderSystemUI(); + else if (ACTION_IMMERSIVE_MODE.equals(action)) + return immersiveMode(); + else if (ACTION_SET_SYSTEM_UI_VISIBILITY.equals(action)) + return setSystemUiVisibility(args.getInt(0)); + + return false; + } + + protected void resetWindow() + { + decorView.setOnFocusChangeListener(null); + decorView.setOnSystemUiVisibilityChangeListener(null); + + window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); + } + + /** + * Are any of the features of this plugin supported? + */ + protected boolean isSupported() + { + boolean supported = Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH; + + PluginResult res = new PluginResult(PluginResult.Status.OK, supported); + context.sendPluginResult(res); + return supported; + } + + /** + * Is immersive mode supported? + */ + protected boolean isImmersiveModeSupported() + { + boolean supported = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; + + PluginResult res = new PluginResult(PluginResult.Status.OK, supported); + context.sendPluginResult(res); + return supported; + } + + /** + * The width of the screen in immersive mode + */ + protected boolean immersiveWidth() + { + activity.runOnUiThread(new Runnable() + { + @Override + public void run() + { + try + { + Point outSize = new Point(); + + decorView.getDisplay().getRealSize(outSize); + + PluginResult res = new PluginResult(PluginResult.Status.OK, outSize.x); + context.sendPluginResult(res); + } + catch (Exception e) + { + context.error(e.getMessage()); + } + } + }); + + return true; + } + + /** + * The height of the screen in immersive mode + */ + protected boolean immersiveHeight() + { + activity.runOnUiThread(new Runnable() + { + @Override + public void run() + { + try + { + Point outSize = new Point(); + + decorView.getDisplay().getRealSize(outSize); + + PluginResult res = new PluginResult(PluginResult.Status.OK, outSize.y); + context.sendPluginResult(res); + } + catch (Exception e) + { + context.error(e.getMessage()); + } + } + }); + + return true; + } + + /** + * Hide system UI until user interacts + */ + protected boolean leanMode() + { + if (!isSupported()) + { + context.error("Not supported"); + return false; + } + + activity.runOnUiThread(new Runnable() + { + @Override + public void run() + { + try + { + resetWindow(); + + int uiOptions = + View.SYSTEM_UI_FLAG_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_FULLSCREEN + | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN + | View.SYSTEM_UI_FLAG_LAYOUT_STABLE; + + mLastSystemUIVisibility = uiOptions; + decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() + { + @Override + public void onSystemUiVisibilityChange(int visibility) + { + if((mLastSystemUIVisibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0 + && (visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) { + resetHideTimer(); + } + mLastSystemUIVisibility = visibility; + } + }); + + decorView.setSystemUiVisibility(uiOptions); + + context.success(); + } + catch (Exception e) + { + context.error(e.getMessage()); + } + } + }); + + return true; + } + + private void resetHideTimer() { + // First cancel any queued events - i.e. resetting the countdown clock + mLeanBackHandler.removeCallbacks(mEnterLeanback); + // And fire the event in 3s time + mLeanBackHandler.postDelayed(mEnterLeanback, 3000); + } + + /** + * Show system UI + */ + protected boolean showSystemUI() + { + if (!isSupported()) + { + context.error("Not supported"); + return false; + } + + activity.runOnUiThread(new Runnable() + { + @Override + public void run() + { + try + { + resetWindow(); + + // Remove translucent theme from bars + + window.clearFlags + ( + WindowManager.LayoutParams.FLAG_FULLSCREEN + | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION + | WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS + ); + + // Update system UI + + decorView.setOnSystemUiVisibilityChangeListener(null); + decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE); + + PluginResult res = new PluginResult(PluginResult.Status.OK, true); + context.sendPluginResult(res); + + context.success(); + } + catch (Exception e) + { + context.error(e.getMessage()); + } + } + }); + + return true; + } + + /** + * Extend your app underneath the status bar (Android 4.4+ only) + */ + protected boolean showUnderStatusBar() + { + if (!isImmersiveModeSupported()) + { + context.error("Not supported"); + return false; + } + + activity.runOnUiThread(new Runnable() + { + @Override + public void run() + { + try + { + resetWindow(); + + // Make the status bar translucent + + window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); + + // Extend view underneath status bar + + int uiOptions = + View.SYSTEM_UI_FLAG_LAYOUT_STABLE + | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; + + decorView.setSystemUiVisibility(uiOptions); + + context.success(); + } + catch (Exception e) + { + context.error(e.getMessage()); + } + } + }); + + return true; + } + + /** + * Extend your app underneath the system UI (Android 4.4+ only) + */ + protected boolean showUnderSystemUI() + { + if (!isImmersiveModeSupported()) + { + context.error("Not supported"); + return false; + } + + activity.runOnUiThread(new Runnable() + { + @Override + public void run() + { + try + { + resetWindow(); + + // Make the status and nav bars translucent + + window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); + window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); + + // Extend view underneath status and nav bars + + int uiOptions = + View.SYSTEM_UI_FLAG_LAYOUT_STABLE + | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION; + + decorView.setSystemUiVisibility(uiOptions); + + context.success(); + } + catch (Exception e) + { + context.error(e.getMessage()); + } + } + }); + + return true; + } + + /** + * Hide system UI and switch to immersive mode (Android 4.4+ only) + */ + protected boolean immersiveMode() + { + if (!isImmersiveModeSupported()) + { + context.error("Not supported"); + return false; + } + + activity.runOnUiThread(new Runnable() + { + @Override + public void run() + { + try + { + resetWindow(); + + final int uiOptions = + View.SYSTEM_UI_FLAG_LAYOUT_STABLE + | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN + | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_FULLSCREEN + | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; + + window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); + decorView.setSystemUiVisibility(uiOptions); + + decorView.setOnFocusChangeListener(new View.OnFocusChangeListener() + { + @Override + public void onFocusChange(View v, boolean hasFocus) + { + if (hasFocus) + { + decorView.setSystemUiVisibility(uiOptions); + } + } + }); + + decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() + { + @Override + public void onSystemUiVisibilityChange(int visibility) + { + decorView.setSystemUiVisibility(uiOptions); + } + }); + + context.success(); + } + catch (Exception e) + { + context.error(e.getMessage()); + } + } + }); + + return true; + } + + protected boolean setSystemUiVisibility(final int visibility) + { + if (!isSupported()) + { + context.error("Not supported"); + return false; + } + + activity.runOnUiThread(new Runnable() + { + @Override + public void run() + { + try + { + resetWindow(); + decorView.setSystemUiVisibility(visibility); + context.success(); + } + catch (Exception e) + { + context.error(e.getMessage()); + } + } + }); + + return true; + } + + private void setStatusBarBackgroundColor(final String colorPref) { + if (Build.VERSION.SDK_INT >= 21) { + if (colorPref != null && !colorPref.isEmpty()) { + final Window window = cordova.getActivity().getWindow(); + // Method and constants not available on all SDKs but we want to be able to compile this code with any SDK + window.clearFlags(0x04000000); // SDK 19: WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); + window.addFlags(0x80000000); // SDK 21: WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); + try { + // Using reflection makes sure any 5.0+ device will work without having to compile with SDK level 21 + window.getClass().getDeclaredMethod("setStatusBarColor", int.class).invoke(window, Color.parseColor(colorPref)); + } catch (IllegalArgumentException ignore) { + } catch (Exception ignore) { + } + } + } + } + +} diff --git a/plugins/cordova-plugin-fullscreen/www/AndroidFullScreen.js b/plugins/cordova-plugin-fullscreen/www/AndroidFullScreen.js new file mode 100644 index 0000000..3af2a12 --- /dev/null +++ b/plugins/cordova-plugin-fullscreen/www/AndroidFullScreen.js @@ -0,0 +1,79 @@ +(function(window, undefined) +{ + 'use strict'; + + var AndroidFullScreen = + { + SYSTEM_UI_FLAG_FULLSCREEN: 4, + SYSTEM_UI_FLAG_HIDE_NAVIGATION: 2, + SYSTEM_UI_FLAG_IMMERSIVE: 2048, + SYSTEM_UI_FLAG_IMMERSIVE_STICKY: 4096, + SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN: 1024, + SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION: 512, + SYSTEM_UI_FLAG_LAYOUT_STABLE: 256, + SYSTEM_UI_FLAG_LIGHT_STATUS_BAR: 8192, + SYSTEM_UI_FLAG_LOW_PROFILE: 1, + SYSTEM_UI_FLAG_VISIBLE: 0, + + isSupported: function(successFunction, errorFunction) + { + cordova.exec(successFunction, errorFunction, 'AndroidFullScreen', 'isSupported', []); + }, + + isImmersiveModeSupported: function(successFunction, errorFunction) + { + cordova.exec(successFunction, errorFunction, 'AndroidFullScreen', 'isImmersiveModeSupported', []); + }, + + immersiveWidth: function(successFunction, errorFunction) + { + cordova.exec(successFunction, errorFunction, 'AndroidFullScreen', 'immersiveWidth', []); + }, + + immersiveHeight: function(successFunction, errorFunction) + { + cordova.exec(successFunction, errorFunction, 'AndroidFullScreen', 'immersiveHeight', []); + }, + + leanMode: function(successFunction, errorFunction) + { + cordova.exec(successFunction, errorFunction, 'AndroidFullScreen', 'leanMode', []); + }, + + showSystemUI: function(successFunction, errorFunction) + { + cordova.exec(successFunction, errorFunction, 'AndroidFullScreen', 'showSystemUI', []); + }, + + showUnderStatusBar: function(successFunction, errorFunction) + { + cordova.exec(successFunction, errorFunction, 'AndroidFullScreen', 'showUnderStatusBar', []); + }, + + showUnderSystemUI: function(successFunction, errorFunction) + { + cordova.exec(successFunction, errorFunction, 'AndroidFullScreen', 'showUnderSystemUI', []); + }, + + immersiveMode: function(successFunction, errorFunction) + { + cordova.exec(successFunction, errorFunction, 'AndroidFullScreen', 'immersiveMode', []); + }, + + /** + * @see https://developer.android.com/reference/android/view/View.html#setSystemUiVisibility(int) + */ + setSystemUiVisibility: function(visibility, successFunction, errorFunction) + { + cordova.exec(successFunction, errorFunction, 'AndroidFullScreen', 'setSystemUiVisibility', [visibility || 0]); + } + + }; + + cordova.addConstructor(function() + { + window.AndroidFullScreen = AndroidFullScreen; + return window.AndroidFullScreen; + }); + +})(window); diff --git a/plugins/cordova-plugin-geolocation/CONTRIBUTING.md b/plugins/cordova-plugin-geolocation/CONTRIBUTING.md new file mode 100644 index 0000000..4c8e6a5 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/CONTRIBUTING.md @@ -0,0 +1,37 @@ + + +# Contributing to Apache Cordova + +Anyone can contribute to Cordova. And we need your contributions. + +There are multiple ways to contribute: report bugs, improve the docs, and +contribute code. + +For instructions on this, start with the +[contribution overview](http://cordova.apache.org/contribute/). + +The details are explained there, but the important items are: + - Sign and submit an Apache ICLA (Contributor License Agreement). + - Have a Jira issue open that corresponds to your contribution. + - Run the tests so your patch doesn't break existing functionality. + +We look forward to your contributions! diff --git a/plugins/cordova-plugin-geolocation/LICENSE b/plugins/cordova-plugin-geolocation/LICENSE new file mode 100644 index 0000000..7a4a3ea --- /dev/null +++ b/plugins/cordova-plugin-geolocation/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/plugins/cordova-plugin-geolocation/NOTICE b/plugins/cordova-plugin-geolocation/NOTICE new file mode 100644 index 0000000..8ec56a5 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/NOTICE @@ -0,0 +1,5 @@ +Apache Cordova +Copyright 2012 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). diff --git a/plugins/cordova-plugin-geolocation/README.md b/plugins/cordova-plugin-geolocation/README.md new file mode 100644 index 0000000..50af37c --- /dev/null +++ b/plugins/cordova-plugin-geolocation/README.md @@ -0,0 +1,769 @@ +--- +title: Geolocation +description: Access GPS data. +--- + + +|Android 4.4|Android 5.1|Android 6.0|iOS 9.3|iOS 10.0|Windows 10 Store|Travis CI| +|:-:|:-:|:-:|:-:|:-:|:-:|:-:| +|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-4.4,PLUGIN=cordova-plugin-geolocation)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-4.4,PLUGIN=cordova-plugin-geolocation/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-5.1,PLUGIN=cordova-plugin-geolocation)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-5.1,PLUGIN=cordova-plugin-geolocation/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-6.0,PLUGIN=cordova-plugin-geolocation)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-6.0,PLUGIN=cordova-plugin-geolocation/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=ios-9.3,PLUGIN=cordova-plugin-geolocation)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios-9.3,PLUGIN=cordova-plugin-geolocation/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=ios-10.0,PLUGIN=cordova-plugin-geolocation)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios-10.0,PLUGIN=cordova-plugin-geolocation/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-geolocation)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-geolocation/)|[![Build Status](https://travis-ci.org/apache/cordova-plugin-geolocation.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-geolocation)| + +# cordova-plugin-geolocation + +This plugin provides information about the device's location, such as +latitude and longitude. + +Common sources of location information include +Global Positioning System (GPS) and location inferred from network +signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, +and GSM/CDMA cell IDs. There is no guarantee that the API returns the +device's actual location. + +> To get a few ideas, check out the [sample](#sample) at the bottom of this page or go straight to the [reference](#reference) content. + +This API is based on the +[W3C Geolocation API Specification](http://dev.w3.org/geo/api/spec-source.html), +and only executes on devices that don't already provide an implementation. + +__WARNING__: Collection and use of geolocation data +raises important privacy issues. Your app's privacy policy should +discuss how the app uses geolocation data, whether it is shared with +any other parties, and the level of precision of the data (for +example, coarse, fine, ZIP code level, etc.). Geolocation data is +generally considered sensitive because it can reveal user's +whereabouts and, if stored, the history of their travels. +Therefore, in addition to the app's privacy policy, you should +strongly consider providing a just-in-time notice before the app +accesses geolocation data (if the device operating system doesn't do +so already). That notice should provide the same information noted +above, as well as obtaining the user's permission (e.g., by presenting +choices for __OK__ and __No Thanks__). For more information, please +see the [Privacy Guide](http://cordova.apache.org/docs/en/latest/guide/appdev/privacy/index.html). + +This plugin defines a global `navigator.geolocation` object (for platforms +where it is otherwise missing). + +Although the object is in the global scope, features provided by this plugin +are not available until after the `deviceready` event. + +```javascript + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + +``` +## Reference +## Installation + +This requires cordova 5.0+ ( current stable 1.0.0 ) + + cordova plugin add cordova-plugin-geolocation + +Older versions of cordova can still install via the deprecated id ( stale 0.3.12 ) + + cordova plugin add org.apache.cordova.geolocation + +It is also possible to install via repo url directly ( unstable ) + + cordova plugin add https://github.com/apache/cordova-plugin-geolocation.git + +## Supported Platforms + +- Amazon Fire OS +- Android +- BlackBerry 10 +- Firefox OS +- iOS +- Tizen +- Windows Phone 7 and 8 +- Windows + +## Methods + +- navigator.geolocation.getCurrentPosition +- navigator.geolocation.watchPosition +- navigator.geolocation.clearWatch + +## Objects (Read-Only) + +- Position +- PositionError +- Coordinates + +## navigator.geolocation.getCurrentPosition + +Returns the device's current position to the `geolocationSuccess` +callback with a `Position` object as the parameter. If there is an +error, the `geolocationError` callback is passed a +`PositionError` object. + + navigator.geolocation.getCurrentPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + +### Parameters + +- __geolocationSuccess__: The callback that is passed the current position. + +- __geolocationError__: _(Optional)_ The callback that executes if an error occurs. + +- __geolocationOptions__: _(Optional)_ The geolocation options. + + +### Example + +```javascript + + // 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'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + +``` + +### iOS Quirks + + Since iOS 10 it's mandatory to add a `NSLocationWhenInUseUsageDescription` entry in the info.plist. + + `NSLocationWhenInUseUsageDescription` describes the reason that the app accesses the user's location. When the system prompts the user to allow access, this string is displayed as part of the dialog box. To add this entry you can pass the variable `GEOLOCATION_USAGE_DESCRIPTION` on plugin install. + + Example: + `cordova plugin add cordova-plugin-geolocation --variable GEOLOCATION_USAGE_DESCRIPTION="your usage message"` + + If you don't pass the variable, the plugin will add an empty string as value. + +### Android Quirks + +If Geolocation service is turned off the `onError` callback is invoked after `timeout` interval (if specified). +If `timeout` parameter is not specified then no callback is called. + +## navigator.geolocation.watchPosition + +Returns the device's current position when a change in position is detected. +When the device retrieves a new location, the `geolocationSuccess` +callback executes with a `Position` object as the parameter. If +there is an error, the `geolocationError` callback executes with a +`PositionError` object as the parameter. + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + +### Parameters + +- __geolocationSuccess__: The callback that is passed the current position. + +- __geolocationError__: (Optional) The callback that executes if an error occurs. + +- __geolocationOptions__: (Optional) The geolocation options. + +### Returns + +- __String__: returns a watch id that references the watch position interval. The watch id should be used with `navigator.geolocation.clearWatch` to stop watching for changes in position. + +### Example + +```javascript + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '
' + + 'Longitude: ' + position.coords.longitude + '
' + + '
' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + +``` + +## geolocationOptions + +Optional parameters to customize the retrieval of the geolocation +`Position`. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + +### Options + +- __enableHighAccuracy__: Provides a hint that the application needs the best possible results. By default, the device attempts to retrieve a `Position` using network-based methods. Setting this property to `true` tells the framework to use more accurate methods, such as satellite positioning. _(Boolean)_ + +- __timeout__: The maximum length of time (milliseconds) that is allowed to pass from the call to `navigator.geolocation.getCurrentPosition` or `geolocation.watchPosition` until the corresponding `geolocationSuccess` callback executes. If the `geolocationSuccess` callback is not invoked within this time, the `geolocationError` callback is passed a `PositionError.TIMEOUT` error code. (Note that when used in conjunction with `geolocation.watchPosition`, the `geolocationError` callback could be called on an interval every `timeout` milliseconds!) _(Number)_ + +- __maximumAge__: Accept a cached position whose age is no greater than the specified time in milliseconds. _(Number)_ + +### Android Quirks + +If Geolocation service is turned off the `onError` callback is invoked after `timeout` interval (if specified). +If `timeout` parameter is not specified then no callback is called. + +## navigator.geolocation.clearWatch + +Stop watching for changes to the device's location referenced by the +`watchID` parameter. + + navigator.geolocation.clearWatch(watchID); + +### Parameters + +- __watchID__: The id of the `watchPosition` interval to clear. (String) + +### Example + +```javascript + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + +``` + +## Position + +Contains `Position` coordinates and timestamp, created by the geolocation API. + +### Properties + +- __coords__: A set of geographic coordinates. _(Coordinates)_ + +- __timestamp__: Creation timestamp for `coords`. _(DOMTimeStamp)_ + +## Coordinates + +A `Coordinates` object is attached to a `Position` object that is +available to callback functions in requests for the current position. +It contains a set of properties that describe the geographic coordinates of a position. + +### Properties + +* __latitude__: Latitude in decimal degrees. _(Number)_ + +* __longitude__: Longitude in decimal degrees. _(Number)_ + +* __altitude__: Height of the position in meters above the ellipsoid. _(Number)_ + +* __accuracy__: Accuracy level of the latitude and longitude coordinates in meters. _(Number)_ + +* __altitudeAccuracy__: Accuracy level of the altitude coordinate in meters. _(Number)_ + +* __heading__: Direction of travel, specified in degrees counting clockwise relative to the true north. _(Number)_ + +* __speed__: Current ground speed of the device, specified in meters per second. _(Number)_ + +### Amazon Fire OS Quirks + +__altitudeAccuracy__: Not supported by Android devices, returning `null`. + +### Android Quirks + +__altitudeAccuracy__: Not supported by Android devices, returning `null`. + +## PositionError + +The `PositionError` object is passed to the `geolocationError` +callback function when an error occurs with navigator.geolocation. + +### Properties + +- __code__: One of the predefined error codes listed below. + +- __message__: Error message describing the details of the error encountered. + +### Constants + +- `PositionError.PERMISSION_DENIED` + - Returned when users do not allow the app to retrieve position information. This is dependent on the platform. +- `PositionError.POSITION_UNAVAILABLE` + - Returned when the device is unable to retrieve a position. In general, this means the device is not connected to a network or can't get a satellite fix. +- `PositionError.TIMEOUT` + - Returned when the device is unable to retrieve a position within the time specified by the `timeout` included in `geolocationOptions`. When used with `navigator.geolocation.watchPosition`, this error could be repeatedly passed to the `geolocationError` callback every `timeout` milliseconds. + + +## Sample: Get the weather, find stores, and see photos of things nearby with Geolocation ## + +Use this plugin to help users find things near them such as Groupon deals, houses for sale, movies playing, sports and entertainment events and more. + +Here's a "cookbook" of ideas to get you started. In the snippets below, we'll show you some basic ways to add these features to your app. + +* [Get your coordinates](#coords). +* [Get the weather forecast](#weather). +* [Receive updated weather forecasts as you drive around](#receive). +* [See where you are on a map](#see). +* [Find stores near you](#find). +* [See pictures of things around you](#see). + +## Get your geolocation coordinates + +```javascript + +function getWeatherLocation() { + + navigator.geolocation.getCurrentPosition + (onWeatherSuccess, onWeatherError, { enableHighAccuracy: true }); +} + +``` +## Get the weather forecast + +```javascript + +// Success callback for get geo coordinates + +var onWeatherSuccess = function (position) { + + Latitude = position.coords.latitude; + Longitude = position.coords.longitude; + + getWeather(Latitude, Longitude); +} + +// Get weather by using coordinates + +function getWeather(latitude, longitude) { + + // Get a free key at http://openweathermap.org/. Replace the "Your_Key_Here" string with that key. + var OpenWeatherAppKey = "Your_Key_Here"; + + var queryString = + 'http://api.openweathermap.org/data/2.5/weather?lat=' + + latitude + '&lon=' + longitude + '&appid=' + OpenWeatherAppKey + '&units=imperial'; + + $.getJSON(queryString, function (results) { + + if (results.weather.length) { + + $.getJSON(queryString, function (results) { + + if (results.weather.length) { + + $('#description').text(results.name); + $('#temp').text(results.main.temp); + $('#wind').text(results.wind.speed); + $('#humidity').text(results.main.humidity); + $('#visibility').text(results.weather[0].main); + + var sunriseDate = new Date(results.sys.sunrise); + $('#sunrise').text(sunriseDate.toLocaleTimeString()); + + var sunsetDate = new Date(results.sys.sunrise); + $('#sunset').text(sunsetDate.toLocaleTimeString()); + } + + }); + } + }).fail(function () { + console.log("error getting location"); + }); +} + +// Error callback + +function onWeatherError(error) { + console.log('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); +} + +``` + +## Receive updated weather forecasts as you drive around + +```javascript + +// Watch your changing position + +function watchWeatherPosition() { + + return navigator.geolocation.watchPosition + (onWeatherWatchSuccess, onWeatherError, { enableHighAccuracy: true }); +} + +// Success callback for watching your changing position + +var onWeatherWatchSuccess = function (position) { + + var updatedLatitude = position.coords.latitude; + var updatedLongitude = position.coords.longitude; + + if (updatedLatitude != Latitude && updatedLongitude != Longitude) { + + Latitude = updatedLatitude; + Longitude = updatedLongitude; + + // Calls function we defined earlier. + getWeather(updatedLatitude, updatedLongitude); + } +} + +``` + +## See where you are on a map + +Both Bing and Google have map services. We'll use Google's. You'll need a key but it's free if you're just trying things out. + +Add a reference to the **maps** service. + +```HTML + + + +``` +Then, add code to use it. + +```javascript + +var Latitude = undefined; +var Longitude = undefined; + +// Get geo coordinates + +function getMapLocation() { + + navigator.geolocation.getCurrentPosition + (onMapSuccess, onMapError, { enableHighAccuracy: true }); +} + +// Success callback for get geo coordinates + +var onMapSuccess = function (position) { + + Latitude = position.coords.latitude; + Longitude = position.coords.longitude; + + getMap(Latitude, Longitude); + +} + +// Get map by using coordinates + +function getMap(latitude, longitude) { + + var mapOptions = { + center: new google.maps.LatLng(0, 0), + zoom: 1, + mapTypeId: google.maps.MapTypeId.ROADMAP + }; + + map = new google.maps.Map + (document.getElementById("map"), mapOptions); + + + var latLong = new google.maps.LatLng(latitude, longitude); + + var marker = new google.maps.Marker({ + position: latLong + }); + + marker.setMap(map); + map.setZoom(15); + map.setCenter(marker.getPosition()); +} + +// Success callback for watching your changing position + +var onMapWatchSuccess = function (position) { + + var updatedLatitude = position.coords.latitude; + var updatedLongitude = position.coords.longitude; + + if (updatedLatitude != Latitude && updatedLongitude != Longitude) { + + Latitude = updatedLatitude; + Longitude = updatedLongitude; + + getMap(updatedLatitude, updatedLongitude); + } +} + +// Error callback + +function onMapError(error) { + console.log('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); +} + +// Watch your changing position + +function watchMapPosition() { + + return navigator.geolocation.watchPosition + (onMapWatchSuccess, onMapError, { enableHighAccuracy: true }); +} + +``` + +## Find stores near you + +You can use the same Google key for this. + +Add a reference to the **places** service. + +```HTML + + + +``` + +Then, add code to use it. + +```javascript + +var Map; +var Infowindow; +var Latitude = undefined; +var Longitude = undefined; + +// Get geo coordinates + +function getPlacesLocation() { + navigator.geolocation.getCurrentPosition + (onPlacesSuccess, onPlacesError, { enableHighAccuracy: true }); +} + +// Success callback for get geo coordinates + +var onPlacesSuccess = function (position) { + + Latitude = position.coords.latitude; + Longitude = position.coords.longitude; + + getPlaces(Latitude, Longitude); + +} + +// Get places by using coordinates + +function getPlaces(latitude, longitude) { + + var latLong = new google.maps.LatLng(latitude, longitude); + + var mapOptions = { + + center: new google.maps.LatLng(latitude, longitude), + zoom: 15, + mapTypeId: google.maps.MapTypeId.ROADMAP + + }; + + Map = new google.maps.Map(document.getElementById("places"), mapOptions); + + Infowindow = new google.maps.InfoWindow(); + + var service = new google.maps.places.PlacesService(Map); + service.nearbySearch({ + + location: latLong, + radius: 500, + type: ['store'] + }, foundStoresCallback); + +} + +// Success callback for watching your changing position + +var onPlacesWatchSuccess = function (position) { + + var updatedLatitude = position.coords.latitude; + var updatedLongitude = position.coords.longitude; + + if (updatedLatitude != Latitude && updatedLongitude != Longitude) { + + Latitude = updatedLatitude; + Longitude = updatedLongitude; + + getPlaces(updatedLatitude, updatedLongitude); + } +} + +// Success callback for locating stores in the area + +function foundStoresCallback(results, status) { + + if (status === google.maps.places.PlacesServiceStatus.OK) { + + for (var i = 0; i < results.length; i++) { + + createMarker(results[i]); + + } + } +} + +// Place a pin for each store on the map + +function createMarker(place) { + + var placeLoc = place.geometry.location; + + var marker = new google.maps.Marker({ + map: Map, + position: place.geometry.location + }); + + google.maps.event.addListener(marker, 'click', function () { + + Infowindow.setContent(place.name); + Infowindow.open(Map, this); + + }); +} + +// Error callback + +function onPlacesError(error) { + console.log('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); +} + +// Watch your changing position + +function watchPlacesPosition() { + + return navigator.geolocation.watchPosition + (onPlacesWatchSuccess, onPlacesError, { enableHighAccuracy: true }); +} + +``` + +## See pictures of things around you + +Digital photos can contain geo coordinates that identify where the picture was taken. + +Use Flickr API's to find pictures that folks have taken near you. Like Google services, you'll need a key, but it's free if you just want to try things out. + +```javascript + +var Latitude = undefined; +var Longitude = undefined; + +// Get geo coordinates + +function getPicturesLocation() { + + navigator.geolocation.getCurrentPosition + (onPicturesSuccess, onPicturesError, { enableHighAccuracy: true }); + +} + +// Success callback for get geo coordinates + +var onPicturesSuccess = function (position) { + + Latitude = position.coords.latitude; + Longitude = position.coords.longitude; + + getPictures(Latitude, Longitude); +} + +// Get pictures by using coordinates + +function getPictures(latitude, longitude) { + + $('#pictures').empty(); + + var queryString = + "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=Your_API_Key&lat=" + + latitude + "&lon=" + longitude + "&format=json&jsoncallback=?"; + + $.getJSON(queryString, function (results) { + $.each(results.photos.photo, function (index, item) { + + var photoURL = "http://farm" + item.farm + ".static.flickr.com/" + + item.server + "/" + item.id + "_" + item.secret + "_m.jpg"; + + $('#pictures').append($("").attr("src", photoURL)); + + }); + } + ); +} + +// Success callback for watching your changing position + +var onPicturesWatchSuccess = function (position) { + + var updatedLatitude = position.coords.latitude; + var updatedLongitude = position.coords.longitude; + + if (updatedLatitude != Latitude && updatedLongitude != Longitude) { + + Latitude = updatedLatitude; + Longitude = updatedLongitude; + + getPictures(updatedLatitude, updatedLongitude); + } +} + +// Error callback + +function onPicturesError(error) { + + console.log('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); +} + +// Watch your changing position + +function watchPicturePosition() { + + return navigator.geolocation.watchPosition + (onPicturesWatchSuccess, onPicturesError, { enableHighAccuracy: true }); +} + +``` diff --git a/plugins/cordova-plugin-geolocation/RELEASENOTES.md b/plugins/cordova-plugin-geolocation/RELEASENOTES.md new file mode 100644 index 0000000..d2804c4 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/RELEASENOTES.md @@ -0,0 +1,186 @@ + +# Release Notes + +### 2.4.3 (Apr 27, 2017) +* [CB-12622](https://issues.apache.org/jira/browse/CB-12622) Added **Android 6.0** build badge to `README` +* [CB-12685](https://issues.apache.org/jira/browse/CB-12685) added `package.json` to tests folder + +### 2.4.2 (Feb 28, 2017) +* [CB-12363](https://issues.apache.org/jira/browse/CB-12363) Added build badges for **iOS 9.3** and **iOS 10.0** +* [CB-12230](https://issues.apache.org/jira/browse/CB-12230) Removed **Windows 8.1** build badges + +### 2.4.1 (Dec 07, 2016) +* [CB-12224](https://issues.apache.org/jira/browse/CB-12224) Updated version and RELEASENOTES.md for release 2.4.1 +* corrected KCLAuthorizationStatus error, changed to always removed user of [manager locationServicesEnabled]. Must return [CLLocationManager locationServicesEnabled] or 'none' +* [CB-11962](https://issues.apache.org/jira/browse/CB-11962) (ios) Added variable for setting NSLocationWhenInUseUsageDescription +* [CB-11917](https://issues.apache.org/jira/browse/CB-11917) - Remove pull request template checklist item: "iCLA has been submitted…" +* [CB-11904](https://issues.apache.org/jira/browse/CB-11904) Incremented plugin version. + +### 2.4.0 (Sep 26, 2016) +* **Ubuntu** Fix altitude & accuracies retrieval +* [CB-11875](https://issues.apache.org/jira/browse/CB-11875) added `android.hardware.location.gps` `uses-feature`. + +### 2.3.0 (Sep 08, 2016) +* [CB-11795](https://issues.apache.org/jira/browse/CB-11795) Add 'protective' entry to cordovaDependencies +* Plugin uses `Android Log class` and not `Cordova LOG class` +* Add badges for paramedic builds on Jenkins +* Add pull request template. +* Adding links to reference content and sample content to the top of the readme file +* Update **iOS** geolocation plugin to avoid `THREAD WARNING: ['Geolocation']`, operation occurs in new Thread +* [CB-10996](https://issues.apache.org/jira/browse/CB-10996) Adding front matter to README.md + +### 2.2.0 (Apr 15, 2016) +* Replace `PermissionHelper.java` with `cordova-plugin-compat` +* [CB-10691](https://issues.apache.org/jira/browse/CB-10691) Check the context to avoid null errors +* [CB-10636](https://issues.apache.org/jira/browse/CB-10636) Add `JSHint` for plugins +* Using a fallback epsilon in case `Number.EPSILON` is not defined. +* [CB-10574](https://issues.apache.org/jira/browse/CB-10574) MobileSpec can't get results for **WP8.1** Builds + +### 2.1.0 (Jan 15, 2016) +* [CB-10319](https://issues.apache.org/jira/browse/CB-10319) **Android** Adding reflective helper methods for permission requests +* [CB-8523](https://issues.apache.org/jira/browse/CB-8523) Fixed accuracy when `enableHighAccuracy: false` on **iOS**. +* [CB-10286](https://issues.apache.org/jira/browse/CB-10286) Don't skip automatic tests on **Android** devices +* [CB-10277](https://issues.apache.org/jira/browse/CB-10277) Error callback should be called w/ `PositionError` when location access is denied +* [CB-10285](https://issues.apache.org/jira/browse/CB-10285) Added tests for `PositionError` constants +* [CB-10278](https://issues.apache.org/jira/browse/CB-10278) geolocation `watchPosition` doesn't return `watchID` string +* [CB-8443](https://issues.apache.org/jira/browse/CB-8443) **Android** nothing happens if `GPS` is turned off +* [CB-10204](https://issues.apache.org/jira/browse/CB-10204) Fix `getCurrentPosition` options on **Android** +* [CB-7146](https://issues.apache.org/jira/browse/CB-7146) Remove built-in `WebView navigator.geolocation` manual tests +* [CB-2845](https://issues.apache.org/jira/browse/CB-2845) `PositionError` constants not attached to prototype as specified in W3C document + +### 2.0.0 (Nov 18, 2015) +* [CB-10035](https://issues.apache.org/jira/browse/CB-10035) Updated `RELEASENOTES` to be newest to oldest +* [CB-9907](https://issues.apache.org/jira/browse/CB-9907) Handle **iOS** tests that fail when ios simulator does not have a location +* [CB-8826](https://issues.apache.org/jira/browse/CB-8826) Check for `NSLocationWhenInUseUsageDescription` first +* [CB-9105](https://issues.apache.org/jira/browse/CB-9105): Fixing `JS` errors in the shim +* Added support for new permissions model for **Android 6.0** aka **Marshmallow** +* Expect `lastPosition` to have a `timestamp` that is already in `msecs` +* [CB-4596](https://issues.apache.org/jira/browse/CB-4596) Date objects are supposed to be `DOMTimeStamp` +* Fixing contribute link. +* [CB-9355](https://issues.apache.org/jira/browse/CB-9355) Fix Geolocation plugin start watch fail related to unset `MovementThreshold` on **Windows 10** + +### 1.0.1 (Jun 17, 2015) +* [CB-9128](https://issues.apache.org/jira/browse/CB-9128) cordova-plugin-geolocation documentation translation: cordova-plugin-geolocation +* fix npm md issue +* [CB-8845](https://issues.apache.org/jira/browse/CB-8845) Updated comment why Android tests are currently pended +* [CB-8845](https://issues.apache.org/jira/browse/CB-8845) Pended tests for Android +* Add more install text for legacy versions of cordova tools. This closes #36 + +### 1.0.0 (Apr 15, 2015) +* [CB-8746](https://issues.apache.org/jira/browse/CB-8746) gave plugin major version bump +* [CB-8683](https://issues.apache.org/jira/browse/CB-8683) changed plugin-id to pacakge-name +* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) properly updated translated docs to use new id +* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) updated translated docs to use new id +* Use TRAVIS_BUILD_DIR, install paramedic by npm +* [CB-8681](https://issues.apache.org/jira/browse/CB-8681) Fixed occasional test failures +* docs: added Windows to supported platforms +* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) Updated Readme +* [CB-8659](https://issues.apache.org/jira/browse/CB-8659): ios: 4.0.x Compatibility: Remove use of initWebView method +* [CB-8659](https://issues.apache.org/jira/browse/CB-8659): ios: 4.0.x Compatibility: Remove use of deprecated headers +* Wrong parameter in Firefox OS plugin +* [CB-8568](https://issues.apache.org/jira/browse/CB-8568) Integrate TravisCI +* [CB-8438](https://issues.apache.org/jira/browse/CB-8438) cordova-plugin-geolocation documentation translation: cordova-plugin-geolocation +* [CB-8538](https://issues.apache.org/jira/browse/CB-8538) Added package.json file +* [CB-8443](https://issues.apache.org/jira/browse/CB-8443) Geolocation tests fail on Windows due to done is called multiple times + +### 0.3.12 (Feb 04, 2015) +* [CB-8351](https://issues.apache.org/jira/browse/CB-8351) ios: Use argumentForIndex rather than NSArray extension + +### 0.3.11 (Dec 02, 2014) +* Do not stop updating location when the error is `kCLErrorLocationUnknown` +* [CB-8094](https://issues.apache.org/jira/browse/CB-8094) Pended auto tests for **Windows** Store since they require user interaction +* [CB-8085](https://issues.apache.org/jira/browse/CB-8085) Fix geolocation plugin on **Windows** +* [CB-7977](https://issues.apache.org/jira/browse/CB-7977) Mention `deviceready` in plugin docs +* [CB-7700](https://issues.apache.org/jira/browse/CB-7700) cordova-plugin-geolocation documentation translation: cordova-plugin-geolocation + +### 0.3.10 (Sep 17, 2014) +* [CB-7556](https://issues.apache.org/jira/browse/CB-7556) iOS: Clearing all Watches does not stop Location Services +* [CB-7158](https://issues.apache.org/jira/browse/CB-7158) Fix geolocation for ios 8 +* Revert [CB-6911](https://issues.apache.org/jira/browse/CB-6911) partially (keeping Info.plist key installation for iOS 8) +* [CB-6911](https://issues.apache.org/jira/browse/CB-6911) Geolocation fails in iOS 8 +* [CB-5114](https://issues.apache.org/jira/browse/CB-5114) **Windows 8.1** - Use a new proxy as old geolocation methods is deprecated +* [CB-5114](https://issues.apache.org/jira/browse/CB-5114) Append **Windows 8.1** into plugin.xml + Optimize Windows 8 Geolocation proxy +* Renamed test dir, added nested plugin.xml +* added documentation for manual tests +* [CB-7146](https://issues.apache.org/jira/browse/CB-7146) Added manual tests +* Removed js-module for tests from plugin.xml +* Changing cdvtest format to use module exports +* register tests using new style +* Convert tests to new style +* Removed amazon-fireos code for geolocation. +* [CB-7571](https://issues.apache.org/jira/browse/CB-7571) Bump version of nested plugin to match parent plugin + +### 0.3.9 (Aug 06, 2014) +* **FFOS** update GeolocationProxy.js +* [CB-7187](https://issues.apache.org/jira/browse/CB-7187) ios: Add explicit dependency on CoreLocation.framework +* [CB-7187](https://issues.apache.org/jira/browse/CB-7187) Delete unused #import of CDVShared.h +* [CB-6127](https://issues.apache.org/jira/browse/CB-6127) Updated translations for docs +* ios: Changed distanceFilter from none to 5 meters, prevents it from spamming the callback even though nothing changed. + +### 0.3.8 (Jun 05, 2014) +* [CB-6127](https://issues.apache.org/jira/browse/CB-6127) Spanish and French Translations added. Github close #14 +* [CB-6804](https://issues.apache.org/jira/browse/CB-6804) Add license +* [CB-5416](https://issues.apache.org/jira/browse/CB-5416) - Adding support for auto-managing permissions +* [CB-6491](https://issues.apache.org/jira/browse/CB-6491) add CONTRIBUTING.md +* pass by only coords +* proper implementation for firefoxos +* call FxOS's getCurrentProxy added + +### 0.3.7 (Apr 17, 2014) +* [CB-6422](https://issues.apache.org/jira/browse/CB-6422): [windows8] use cordova/exec/proxy +* [CB-6212](https://issues.apache.org/jira/browse/CB-6212): [iOS] fix warnings compiled under arm64 64-bit +* [CB-5977](https://issues.apache.org/jira/browse/CB-5977): [android] Removing the Android Geolocation Code. Mission Accomplished. +* [CB-6460](https://issues.apache.org/jira/browse/CB-6460): Update license headers +* Add NOTICE file + +### 0.3.6 (Feb 05, 2014) +* add ubuntu platform support +* [CB-5326](https://issues.apache.org/jira/browse/CB-5326) adding FFOS permission and updating supported platforms +* [CB-5729](https://issues.apache.org/jira/browse/CB-5729) [BlackBerry10] Update GeolocationProxy to return collapsed object + +### 0.3.5 (Jan 02, 2014) +* [CB-5658](https://issues.apache.org/jira/browse/CB-5658) Add doc/index.md for Geolocation plugin +* windows8: adds missing reference to PositionError (w/o it the app crashes) +* Removing incorrectly added closing comments for wp7 platform in plugin.xml + +### 0.3.4 (Dec 4, 2013) +* Append proxy to platform definition in plugin.xml +* Append windows 8 Geolocation proxy +* Code clean-up for android src. +* Updated amazon-fireos platform + reverting some of the fixes in android code. +* Added amazon-fireos platform + some of the fixes in android code. +* [CB-5334](https://issues.apache.org/jira/browse/CB-5334) [BlackBerry10] Use command proxy +* call FxOS's getCurrentProxy added +* pass by only coords +* proper implementation for firefoxos + +### 0.3.3 (Oct 28, 2013) +* [CB-5128](https://issues.apache.org/jira/browse/CB-5128): add repo + issue tag to plugin.xml for geolocation plugin +* [CB-4915](https://issues.apache.org/jira/browse/CB-4915) Incremented plugin version on dev branch. + +### 0.3.2 (Sept 25, 2013) +* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) bumping&resetting version +* [BlackBerry10] removed uneeded permission tags in plugin.xml +* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) renaming org.apache.cordova.core.geolocation to org.apache.cordova.geolocation + +### 0.3.0 (Sept 5, 2013) +* Added support for windows 8 (Adds required permission) diff --git a/plugins/cordova-plugin-geolocation/doc/de/README.md b/plugins/cordova-plugin-geolocation/doc/de/README.md new file mode 100644 index 0000000..17e14a5 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/doc/de/README.md @@ -0,0 +1,268 @@ + + +# cordova-plugin-geolocation + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-geolocation.svg)](https://travis-ci.org/apache/cordova-plugin-geolocation) + +Dieses Plugin bietet Informationen über das Gerät an den Speicherort, z. B. breiten- und Längengrad. Gemeinsame Quellen von Standortinformationen sind Global Positioning System (GPS) und Lage von Netzwerk-Signale wie IP-Adresse, RFID, WLAN und Bluetooth MAC-Adressen und GSM/CDMA Zelle IDs abgeleitet. Es gibt keine Garantie, dass die API des Geräts tatsächliche Position zurückgibt. + +Diese API basiert auf der [W3C Geolocation API-Spezifikation](http://dev.w3.org/geo/api/spec-source.html), und nur auf Geräten, die nicht bereits eine Implementierung bieten führt. + +**Warnung**: Erhebung und Nutzung von Geolocation-Daten wichtige Privatsphäre wirft. Wie die app benutzt Geolocation-Daten, Ihre app-Datenschutzrichtlinien zu diskutieren, ob es mit allen anderen Parteien und das Niveau der Genauigkeit der Daten (z. B. grob, fein, Postleitzahl, etc..) freigegeben ist. Geolocation-Daten gilt allgemein als empfindlich, weil es den Aufenthaltsort des Benutzers erkennen lässt und wenn gespeichert, die Geschichte von ihren Reisen. Daher neben der app-Privacy Policy sollten stark Sie Bereitstellung einer just-in-Time-Bekanntmachung, bevor die app Geolocation-Daten zugreift (wenn das Betriebssystem des Geräts bereits tun nicht). Diese Benachrichtigung sollte der gleichen Informationen, die vorstehend, sowie die Zustimmung des Benutzers (z.B. durch Präsentation Entscheidungen für das **OK** und **Nein danke**). Weitere Informationen finden Sie in der Datenschutz-Guide. + +Dieses Plugin definiert eine globale `navigator.geolocation`-Objekt (für Plattformen, bei denen es sonst fehlt). + +Obwohl das Objekt im globalen Gültigkeitsbereich ist, stehen Features von diesem Plugin nicht bis nach dem `deviceready`-Ereignis. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + + +## Installation + +Dies erfordert Cordova 5.0 + (aktuelle stabile 1.0.0) + + cordova plugin add cordova-plugin-geolocation + + +Ältere Versionen von Cordova können noch über die veraltete Id (veraltete 0.3.12) installieren. + + cordova plugin add org.apache.cordova.geolocation + + +Es ist auch möglich, über Repo Url direkt zu installieren (unstable) + + cordova plugin add https://github.com/apache/cordova-plugin-geolocation.git + + +## Unterstützte Plattformen + + * Amazon Fire OS + * Android + * BlackBerry 10 + * Firefox OS + * iOS + * Tizen + * Windows Phone 7 und 8 + * Windows 8 + * Windows + +## Methoden + + * navigator.geolocation.getCurrentPosition + * navigator.geolocation.watchPosition + * navigator.geolocation.clearWatch + +## Objekte (schreibgeschützt) + + * Position + * Positionsfehler + * Coordinates + +## navigator.geolocation.getCurrentPosition + +Gibt das Gerät aktuelle Position an den `geolocationSuccess`-Rückruf mit einem `Position`-Objekt als Parameter zurück. Wenn ein Fehler vorliegt, wird der Rückruf `geolocationError` ein `PositionError`-Objekt übergeben. + + navigator.geolocation.getCurrentPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### Parameter + + * **GeolocationSuccess**: der Rückruf, der die aktuelle Position übergeben wird. + + * **GeolocationError**: *(Optional)* der Rückruf, der ausgeführt wird, wenn ein Fehler auftritt. + + * **GeolocationOptions**: *(Optional)* die Geolocation-Optionen. + +### Beispiel + + // 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'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + + +## navigator.geolocation.watchPosition + +Gibt das Gerät aktuelle Position zurück, wenn eine Änderung erkannt wird. Wenn das Gerät einen neuen Speicherort abgerufen hat, führt der `geolocationSuccess`-Rückruf mit einer `Position`-Objekt als Parameter. Wenn ein Fehler vorliegt, führt der `geolocationError`-Rückruf mit einem `PositionError`-Objekt als Parameter. + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### Parameter + + * **GeolocationSuccess**: der Rückruf, der die aktuelle Position übergeben wird. + + * **GeolocationError**: (Optional) der Rückruf, der ausgeführt wird, wenn ein Fehler auftritt. + + * **GeolocationOptions**: (Optional) die Geolocation-Optionen. + +### Gibt + + * **String**: gibt eine Uhr-Id, die das Uhr Position Intervall verweist zurück. Die Uhr-Id sollte verwendet werden, mit `navigator.geolocation.clearWatch` , gerade für Änderungen zu stoppen. + +### Beispiel + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '
' + + 'Longitude: ' + position.coords.longitude + '
' + + '
' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +Optionalen Parametern, um das Abrufen von Geolocation `Position`. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### Optionen + + * **EnableHighAccuracy**: stellt einen Hinweis, dass die Anwendung die bestmöglichen Ergebnisse benötigt. Standardmäßig versucht das Gerät abzurufen ein `Position` mit netzwerkbasierte Methoden. Wenn diese Eigenschaft auf `true` erzählt den Rahmenbedingungen genauere Methoden, z. B. Satellitenortung verwenden. *(Boolean)* + + * **Timeout**: die maximale Länge der Zeit (in Millisekunden), die zulässig ist, übergeben Sie den Aufruf von `navigator.geolocation.getCurrentPosition` oder `geolocation.watchPosition` bis zu den entsprechenden `geolocationSuccess` Rückruf führt. Wenn die `geolocationSuccess` Rückruf wird nicht aufgerufen, in dieser Zeit die `geolocationError` Rückruf wird übergeben ein `PositionError.TIMEOUT` Fehlercode. (Beachten Sie, dass in Verbindung mit `geolocation.watchPosition` , die `geolocationError` Rückruf könnte auf ein Intervall aufgerufen werden alle `timeout` Millisekunden!) *(Anzahl)* + + * **MaximumAge**: eine zwischengespeicherte Position, deren Alter nicht größer als die angegebene Zeit in Millisekunden ist, zu akzeptieren. *(Anzahl)* + +### Android Eigenarten + +Android 2.x-Emulatoren geben ein Geolocation-Ergebnis nicht zurück, es sei denn, die `EnableHighAccuracy`-Option auf `true` festgelegt ist. + +## navigator.geolocation.clearWatch + +Stoppen Sie, gerade für Änderungen an dem Gerät Speicherort verweist mithilfe des Parameters `watchID`. + + navigator.geolocation.clearWatch(watchID); + + +### Parameter + + * **WatchID**: die Id der `watchPosition` Intervall löschen. (String) + +### Beispiel + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +Enthält `Position` koordinaten und Timestamp, erstellt von der Geolocation API. + +### Eigenschaften + + * **coords**: eine Reihe von geographischen Koordinaten. *(Coordinates)* + + * **timestamp**: Zeitstempel der Erstellung für `coords` . *(DOMTimeStamp)* + +## Coordinates + +Ein `Coordinates`-Objekt ist ein `Position`-Objekt zugeordnet, die Callback-Funktionen in Anforderungen für die aktuelle Position zur Verfügung steht. Es enthält eine Reihe von Eigenschaften, die die geographischen Koordinaten von einer Position zu beschreiben. + +### Eigenschaften + + * **latitude**: Latitude in Dezimalgrad. *(Anzahl)* + + * **longitude**: Länge in Dezimalgrad. *(Anzahl)* + + * **altitude**: Höhe der Position in Meter über dem Ellipsoid. *(Anzahl)* + + * **accuracy**: Genauigkeit der breiten- und Längengrad Koordinaten in Metern. *(Anzahl)* + + * **AltitudeAccuracy**: Genauigkeit der Koordinate Höhe in Metern. *(Anzahl)* + + * **heading**: Fahrtrichtung, angegeben in Grad relativ zu den Norden im Uhrzeigersinn gezählt. *(Anzahl)* + + * **speed**: aktuelle Geschwindigkeit über Grund des Geräts, in Metern pro Sekunde angegeben. *(Anzahl)* + +### Amazon Fire OS Macken + +**altitudeAccuracy**: von Android-Geräten, Rückgabe `null` nicht unterstützt. + +### Android Eigenarten + +**altitudeAccuracy**: von Android-Geräten, Rückgabe `null` nicht unterstützt. + +## Positionsfehler + +Das `PositionError`-Objekt wird an die `geolocationError`-Callback-Funktion übergeben, tritt ein Fehler mit navigator.geolocation. + +### Eigenschaften + + * **Code**: einer der vordefinierten Fehlercodes aufgeführt. + + * **Nachricht**: Fehlermeldung, die die Informationen über den aufgetretenen Fehler beschreibt. + +### Konstanten + + * `PositionError.PERMISSION_DENIED` + * Zurückgegeben, wenn Benutzer erlauben nicht die app Positionsinformationen abgerufen werden. Dies ist abhängig von der Plattform. + * `PositionError.POSITION_UNAVAILABLE` + * Zurückgegeben, wenn das Gerät nicht in der Lage, eine Position abzurufen ist. Im Allgemeinen bedeutet dies, dass das Gerät nicht mit einem Netzwerk verbunden ist oder ein Satelliten-Update kann nicht abgerufen werden. + * `PositionError.TIMEOUT` + * Zurückgegeben, wenn das Gerät nicht in der Lage, eine Position innerhalb der festgelegten Zeit abzurufen ist die `timeout` enthalten `geolocationOptions` . Bei Verwendung mit `navigator.geolocation.watchPosition` , könnte dieser Fehler wiederholt übergeben werden, zu der `geolocationError` Rückruf jedes `timeout` Millisekunden. \ No newline at end of file diff --git a/plugins/cordova-plugin-geolocation/doc/de/index.md b/plugins/cordova-plugin-geolocation/doc/de/index.md new file mode 100644 index 0000000..92b2079 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/doc/de/index.md @@ -0,0 +1,255 @@ + + +# cordova-plugin-geolocation + +Dieses Plugin bietet Informationen über das Gerät an den Speicherort, z. B. breiten- und Längengrad. Gemeinsame Quellen von Standortinformationen sind Global Positioning System (GPS) und Lage von Netzwerk-Signale wie IP-Adresse, RFID, WLAN und Bluetooth MAC-Adressen und GSM/CDMA Zelle IDs abgeleitet. Es gibt keine Garantie, dass die API des Geräts tatsächliche Position zurückgibt. + +Diese API basiert auf der [W3C Geolocation API-Spezifikation][1], und nur auf Geräten, die nicht bereits eine Implementierung bieten führt. + + [1]: http://dev.w3.org/geo/api/spec-source.html + +**Warnung**: Erhebung und Nutzung von Geolocation-Daten wichtige Privatsphäre wirft. Wie die app benutzt Geolocation-Daten, Ihre app-Datenschutzrichtlinien zu diskutieren, ob es mit allen anderen Parteien und das Niveau der Genauigkeit der Daten (z. B. grob, fein, Postleitzahl, etc..) freigegeben ist. Geolocation-Daten gilt allgemein als empfindlich, weil es den Aufenthaltsort des Benutzers erkennen lässt und wenn gespeichert, die Geschichte von ihren Reisen. Daher neben der app-Privacy Policy sollten stark Sie Bereitstellung einer just-in-Time-Bekanntmachung, bevor die app Geolocation-Daten zugreift (wenn das Betriebssystem des Geräts bereits tun nicht). Diese Benachrichtigung sollte der gleichen Informationen, die vorstehend, sowie die Zustimmung des Benutzers (z.B. durch Präsentation Entscheidungen für das **OK** und **Nein danke**). Weitere Informationen finden Sie in der Datenschutz-Guide. + +Dieses Plugin definiert eine globale `navigator.geolocation`-Objekt (für Plattformen, bei denen es sonst fehlt). + +Obwohl das Objekt im globalen Gültigkeitsbereich ist, stehen Features von diesem Plugin nicht bis nach dem `deviceready`-Ereignis. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + + +## Installation + + cordova plugin add cordova-plugin-geolocation + + +## Unterstützte Plattformen + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 und 8 +* Windows 8 + +## Methoden + +* navigator.geolocation.getCurrentPosition +* navigator.geolocation.watchPosition +* navigator.geolocation.clearWatch + +## Objekte (schreibgeschützt) + +* Position +* Positionsfehler +* Coordinates + +## navigator.geolocation.getCurrentPosition + +Gibt das Gerät aktuelle Position an den `geolocationSuccess`-Rückruf mit einem `Position`-Objekt als Parameter zurück. Wenn ein Fehler vorliegt, wird der Rückruf `geolocationError` ein `PositionError`-Objekt übergeben. + + navigator.geolocation.getCurrentPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### Parameter + +* **GeolocationSuccess**: der Rückruf, der die aktuelle Position übergeben wird. + +* **GeolocationError**: *(Optional)* der Rückruf, der ausgeführt wird, wenn ein Fehler auftritt. + +* **GeolocationOptions**: *(Optional)* die Geolocation-Optionen. + +### Beispiel + + // 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'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + + +## navigator.geolocation.watchPosition + +Gibt das Gerät aktuelle Position zurück, wenn eine Änderung erkannt wird. Wenn das Gerät einen neuen Speicherort abgerufen hat, führt der `geolocationSuccess`-Rückruf mit einer `Position`-Objekt als Parameter. Wenn ein Fehler vorliegt, führt der `geolocationError`-Rückruf mit einem `PositionError`-Objekt als Parameter. + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### Parameter + +* **GeolocationSuccess**: der Rückruf, der die aktuelle Position übergeben wird. + +* **GeolocationError**: (Optional) der Rückruf, der ausgeführt wird, wenn ein Fehler auftritt. + +* **GeolocationOptions**: (Optional) die Geolocation-Optionen. + +### Gibt + +* **String**: gibt eine Uhr-Id, die das Uhr Position Intervall verweist zurück. Die Uhr-Id sollte verwendet werden, mit `navigator.geolocation.clearWatch` , gerade für Änderungen zu stoppen. + +### Beispiel + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '
' + + 'Longitude: ' + position.coords.longitude + '
' + + '
' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +Optionalen Parametern, um das Abrufen von Geolocation `Position`. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### Optionen + +* **EnableHighAccuracy**: stellt einen Hinweis, dass die Anwendung die bestmöglichen Ergebnisse benötigt. Standardmäßig versucht das Gerät abzurufen ein `Position` mit netzwerkbasierte Methoden. Wenn diese Eigenschaft auf `true` erzählt den Rahmenbedingungen genauere Methoden, z. B. Satellitenortung verwenden. *(Boolean)* + +* **Timeout**: die maximale Länge der Zeit (in Millisekunden), die zulässig ist, übergeben Sie den Aufruf von `navigator.geolocation.getCurrentPosition` oder `geolocation.watchPosition` bis zu den entsprechenden `geolocationSuccess` Rückruf führt. Wenn die `geolocationSuccess` Rückruf wird nicht aufgerufen, in dieser Zeit die `geolocationError` Rückruf wird übergeben ein `PositionError.TIMEOUT` Fehlercode. (Beachten Sie, dass in Verbindung mit `geolocation.watchPosition` , die `geolocationError` Rückruf könnte auf ein Intervall aufgerufen werden alle `timeout` Millisekunden!) *(Anzahl)* + +* **MaximumAge**: eine zwischengespeicherte Position, deren Alter nicht größer als die angegebene Zeit in Millisekunden ist, zu akzeptieren. *(Anzahl)* + +### Android Eigenarten + +Android 2.x-Emulatoren geben ein Geolocation-Ergebnis nicht zurück, es sei denn, die `EnableHighAccuracy`-Option auf `true` festgelegt ist. + +## navigator.geolocation.clearWatch + +Stoppen Sie, gerade für Änderungen an dem Gerät Speicherort verweist mithilfe des Parameters `watchID`. + + navigator.geolocation.clearWatch(watchID); + + +### Parameter + +* **WatchID**: die Id der `watchPosition` Intervall löschen. (String) + +### Beispiel + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +Enthält `Position` koordinaten und Timestamp, erstellt von der Geolocation API. + +### Eigenschaften + +* **coords**: eine Reihe von geographischen Koordinaten. *(Coordinates)* + +* **timestamp**: Zeitstempel der Erstellung für `coords` . *(DOMTimeStamp)* + +## Coordinates + +Ein `Coordinates`-Objekt ist ein `Position`-Objekt zugeordnet, die Callback-Funktionen in Anforderungen für die aktuelle Position zur Verfügung steht. Es enthält eine Reihe von Eigenschaften, die die geographischen Koordinaten von einer Position zu beschreiben. + +### Eigenschaften + +* **latitude**: Latitude in Dezimalgrad. *(Anzahl)* + +* **longitude**: Länge in Dezimalgrad. *(Anzahl)* + +* **altitude**: Höhe der Position in Meter über dem Ellipsoid. *(Anzahl)* + +* **accuracy**: Genauigkeit der breiten- und Längengrad Koordinaten in Metern. *(Anzahl)* + +* **AltitudeAccuracy**: Genauigkeit der Koordinate Höhe in Metern. *(Anzahl)* + +* **heading**: Fahrtrichtung, angegeben in Grad relativ zu den Norden im Uhrzeigersinn gezählt. *(Anzahl)* + +* **speed**: aktuelle Geschwindigkeit über Grund des Geräts, in Metern pro Sekunde angegeben. *(Anzahl)* + +### Amazon Fire OS Macken + +**altitudeAccuracy**: von Android-Geräten, Rückgabe `null` nicht unterstützt. + +### Android Eigenarten + +**altitudeAccuracy**: von Android-Geräten, Rückgabe `null` nicht unterstützt. + +## Positionsfehler + +Das `PositionError`-Objekt wird an die `geolocationError`-Callback-Funktion übergeben, tritt ein Fehler mit navigator.geolocation. + +### Eigenschaften + +* **Code**: einer der vordefinierten Fehlercodes aufgeführt. + +* **Nachricht**: Fehlermeldung, die die Informationen über den aufgetretenen Fehler beschreibt. + +### Konstanten + +* `PositionError.PERMISSION_DENIED` + * Zurückgegeben, wenn Benutzer erlauben nicht die app Positionsinformationen abgerufen werden. Dies ist abhängig von der Plattform. +* `PositionError.POSITION_UNAVAILABLE` + * Zurückgegeben, wenn das Gerät nicht in der Lage, eine Position abzurufen ist. Im Allgemeinen bedeutet dies, dass das Gerät nicht mit einem Netzwerk verbunden ist oder ein Satelliten-Update kann nicht abgerufen werden. +* `PositionError.TIMEOUT` + * Zurückgegeben, wenn das Gerät nicht in der Lage, eine Position innerhalb der festgelegten Zeit abzurufen ist die `timeout` enthalten `geolocationOptions` . Bei Verwendung mit `navigator.geolocation.watchPosition` , könnte dieser Fehler wiederholt übergeben werden, zu der `geolocationError` Rückruf jedes `timeout` Millisekunden. diff --git a/plugins/cordova-plugin-geolocation/doc/es/README.md b/plugins/cordova-plugin-geolocation/doc/es/README.md new file mode 100644 index 0000000..7808a0e --- /dev/null +++ b/plugins/cordova-plugin-geolocation/doc/es/README.md @@ -0,0 +1,266 @@ + + +# cordova-plugin-geolocation + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-geolocation.svg)](https://travis-ci.org/apache/cordova-plugin-geolocation) + +Este plugin proporciona información sobre la ubicación del dispositivo, tales como la latitud y longitud. Fuentes comunes de información de localización incluyen el sistema de posicionamiento Global (GPS) y ubicación deducido de las señales de la red como dirección IP, direcciones de RFID, WiFi y Bluetooth MAC y celulares GSM/CDMA IDs. No hay ninguna garantía de que la API devuelve la ubicación real del dispositivo. + +Esta API se basa en la [Especificación de API de geolocalización W3C](http://dev.w3.org/geo/api/spec-source.html) y sólo se ejecuta en dispositivos que ya no proporcionan una implementación. + +**ADVERTENCIA**: recopilación y uso de datos de geolocalización plantea cuestiones de privacidad importante. Política de privacidad de su aplicación debe discutir cómo la aplicación utiliza los datos de geolocalización, si se comparte con cualquiera de las partes y el nivel de precisión de los datos (por ejemplo, código postal grueso, fino, nivel, etc.). Datos de geolocalización es generalmente considerados sensibles porque puede revelar paradero del usuario y, si está almacenado, la historia de sus viajes. Por lo tanto, además de política de privacidad de la app, fuertemente considere dar un aviso de just-in-time antes de la aplicación tiene acceso a datos de geolocalización (si el sistema operativo del dispositivo ya no hacerlo). Que el aviso debe proporcionar la misma información mencionada, además de obtener un permiso del usuario (por ejemplo, presentando opciones para **Aceptar** y **No gracias**). Para obtener más información, por favor consulte a la guía de privacidad. + +Este plugin define un global `navigator.geolocation` objeto (para plataformas donde falta lo contrario). + +Aunque el objeto está en el ámbito global, características proporcionadas por este plugin no están disponibles hasta después de la `deviceready` evento. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + + +## Instalación + +Esto requiere cordova 5.0 + (1.0.0 estable actual) + + cordova plugin add cordova-plugin-geolocation + + +Las versiones más antiguas de Córdoba todavía pueden instalar mediante el id obsoleto (0.3.12 rancio) + + Cordova plugin agregar org.apache.cordova.geolocation + + +También es posible instalar directamente vía url repo (inestable) + + cordova plugin add https://github.com/apache/cordova-plugin-geolocation.git + + +## Plataformas soportadas + + * Amazon fire OS + * Android + * BlackBerry 10 + * Firefox OS + * iOS + * Tizen + * Windows Phone 7 y 8 + * Windows 8 + * Windows + +## Métodos + + * navigator.geolocation.getCurrentPosition + * navigator.geolocation.watchPosition + * navigator.geolocation.clearWatch + +## Objetos (sólo lectura) + + * Position + * PositionError + * Coordinates + +## navigator.geolocation.getCurrentPosition + +Devuelve la posición actual del dispositivo a la `geolocationSuccess` "callback" con un `Position` objeto como parámetro. Si hay un error, el `geolocationError` "callback" pasa un `PositionError` objeto. + + navigator.geolocation.getCurrentPosition (geolocationSuccess, [geolocationError], [geolocationOptions]); + + +### Parámetros + + * **geolocationSuccess**: la devolución de llamada que se pasa a la posición actual. + + * **geolocationError**: *(opcional)* la devolución de llamada que se ejecuta si se produce un error. + + * **geolocationOptions**: *(opcional)* las opciones de geolocalización. + +### Ejemplo + + // 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'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + + +## navigator.geolocation.watchPosition + +Devuelve la posición actual del dispositivo cuando se detecta un cambio de posición. Cuando el dispositivo recupera una nueva ubicación, el `geolocationSuccess` devolución de llamada se ejecuta con un `Position` objeto como parámetro. Si hay un error, el `geolocationError` devolución de llamada se ejecuta con un `PositionError` objeto como parámetro. + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### Parámetros + + * **geolocationSuccess**: la devolución de llamada que se pasa a la posición actual. + + * **geolocationError**: (opcional) la devolución de llamada que se ejecuta si se produce un error. + + * **geolocationOptions**: opciones (opcional) la geolocalización. + +### Devoluciones + + * **Cadena**: devuelve un identificador de reloj que hace referencia el intervalo de posición del reloj. El id del reloj debe ser utilizado con `navigator.geolocation.clearWatch` para dejar de ver a los cambios de posición. + +### Ejemplo + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '
' + + 'Longitude: ' + position.coords.longitude + '
' + + '
' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +Parámetros opcionales para personalizar la recuperación de la geolocalización`Position`. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### Opciones + + * **enableHighAccuracy**: proporciona una pista que la aplicación necesita los mejores resultados posibles. De forma predeterminada, el dispositivo intentará recuperar un `Position` usando métodos basados en red. Al establecer esta propiedad en `true` dice el marco a utilizar métodos más precisos, como el posicionamiento satelital. *(Boolean)* + + * **tiempo de espera**: la longitud máxima de tiempo (en milisegundos) que está permitido el paso de la llamada a `navigator.geolocation.getCurrentPosition` o `geolocation.watchPosition` hasta el correspondiente `geolocationSuccess` devolución de llamada se ejecuta. Si el `geolocationSuccess` no se invoque "callback" dentro de este tiempo, el `geolocationError` devolución de llamada se pasa un `PositionError.TIMEOUT` código de error. (Tenga en cuenta que cuando se utiliza en conjunción con `geolocation.watchPosition` , el `geolocationError` "callback" podría ser llamado en un intervalo cada `timeout` milisegundos!) *(Número)* + + * **maximumAge**: aceptar un puesto en la memoria caché, cuya edad no es mayor que el tiempo especificado en milisegundos. *(Número)* + +### Rarezas Android + +Emuladores Android 2.x no devuelva un resultado de geolocalización a menos que el `enableHighAccuracy` opción se establece en`true`. + +## navigator.geolocation.clearWatch + +Deja de ver cambios en la ubicación del dispositivo al que hace referencia el `watchID` parámetro. + + navigator.geolocation.clearWatch(watchID); + + +### Parámetros + + * **watchID**: el id del intervalo `watchPosition` para despejar. (String) + +### Ejemplo + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +Contiene `Position` coordenadas y timestamp, creado por la API de geolocalización. + +### Propiedades + + * **coordenadas**: un conjunto de coordenadas geográficas. *(Coordenadas)* + + * **timestamp**: fecha y hora de creación `coords` . *(DOMTimeStamp)* + +## Coordinates + +A `Coordinates` objeto está unido a un `Position` que está disponible para funciones de retrollamada en las solicitudes para la posición actual del objeto. Contiene un conjunto de propiedades que describen las coordenadas geográficas de posición. + +### Propiedades + + * **Latitude**: latitud en grados decimales. *(Número)* + + * **longitud**: longitud en grados decimales. *(Número)* + + * **altitud**: altura de la posición en metros por encima del elipsoide. *(Número)* + + * **exactitud**: nivel de precisión de las coordenadas de latitud y longitud en metros. *(Número)* + + * **altitudeAccuracy**: nivel de precisión de las coordenadas de altitud en metros. *(Número)* + + * **Dirección**: dirección del recorrido, especificado en grados contando hacia la derecha en relación con el norte verdadero. *(Número)* + + * **velocidad**: velocidad actual del dispositivo especificado en metros por segundo. *(Número)* + +### Amazon fuego OS rarezas + +**altitudeAccuracy**: no compatible con dispositivos Android, regresando`null`. + +### Rarezas Android + +**altitudeAccuracy**: no compatible con dispositivos Android, regresando`null`. + +## PositionError + +El `PositionError` objeto se pasa a la `geolocationError` función de devolución de llamada cuando se produce un error con navigator.geolocation. + +### Propiedades + + * **code**: uno de los códigos de error predefinido enumerados a continuación. + + * **mensaje**: mensaje de Error que describe los detalles del error encontrado. + +### Constantes + + * `PositionError.PERMISSION_DENIED` + * Regresó cuando los usuarios no permiten la aplicación recuperar información de la posición. Esto depende de la plataforma. + * `PositionError.POSITION_UNAVAILABLE` + * Regresó cuando el dispositivo es capaz de recuperar una posición. En general, esto significa que el dispositivo no está conectado a una red o no puede obtener una solución vía satélite. + * `PositionError.TIMEOUT` + * Cuando el dispositivo es capaz de recuperar una posición dentro del tiempo especificado por el `timeout` incluido en `geolocationOptions` . Cuando se utiliza con `navigator.geolocation.watchPosition` , este error podría pasar repetidamente a la `geolocationError` "callback" cada `timeout` milisegundos. \ No newline at end of file diff --git a/plugins/cordova-plugin-geolocation/doc/es/index.md b/plugins/cordova-plugin-geolocation/doc/es/index.md new file mode 100644 index 0000000..041f3f8 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/doc/es/index.md @@ -0,0 +1,214 @@ + + +# cordova-plugin-geolocation + +Este plugin proporciona información sobre la ubicación del dispositivo, tales como la latitud y longitud. Fuentes comunes de información de localización incluyen el sistema de posicionamiento Global (GPS) y ubicación deducido de las señales de la red como dirección IP, direcciones de RFID, WiFi y Bluetooth MAC y celulares GSM/CDMA IDs. No hay ninguna garantía de que la API devuelve la ubicación real del dispositivo. + +Esta API se basa en la [Especificación de API de geolocalización W3C][1] y sólo se ejecuta en dispositivos que ya no proporcionan una implementación. + + [1]: http://dev.w3.org/geo/api/spec-source.html + +**ADVERTENCIA**: recopilación y uso de datos de geolocalización plantea cuestiones de privacidad importante. Política de privacidad de su aplicación debe discutir cómo la aplicación utiliza los datos de geolocalización, si se comparte con cualquiera de las partes y el nivel de precisión de los datos (por ejemplo, código postal grueso, fino, nivel, etc.). Datos de geolocalización es generalmente considerados sensibles porque puede revelar paradero del usuario y, si está almacenado, la historia de sus viajes. Por lo tanto, además de política de privacidad de la app, fuertemente considere dar un aviso de just-in-time antes de la aplicación tiene acceso a datos de geolocalización (si el sistema operativo del dispositivo ya no hacerlo). Que el aviso debe proporcionar la misma información mencionada, además de obtener un permiso del usuario (por ejemplo, presentando opciones para **Aceptar** y **No gracias**). Para obtener más información, por favor consulte a la guía de privacidad. + +Este plugin define un global `navigator.geolocation` objeto (para plataformas donde falta lo contrario). + +Aunque el objeto está en el ámbito global, características proporcionadas por este plugin no están disponibles hasta después de la `deviceready` evento. + + document.addEventListener ("deviceready", onDeviceReady, false); + function onDeviceReady() {console.log ("navigator.geolocation funciona bien");} + + +## Instalación + + Cordova plugin agregar cordova-plugin-geolocation + + +## Plataformas soportadas + +* Amazon fire OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 y 8 +* Windows 8 + +## Métodos + +* navigator.geolocation.getCurrentPosition +* navigator.geolocation.watchPosition +* navigator.geolocation.clearWatch + +## Objetos (sólo lectura) + +* Position +* PositionError +* Coordinates + +## navigator.geolocation.getCurrentPosition + +Devuelve la posición actual del dispositivo a la `geolocationSuccess` "callback" con un `Position` objeto como parámetro. Si hay un error, el `geolocationError` "callback" pasa un `PositionError` objeto. + + navigator.geolocation.getCurrentPosition (geolocationSuccess, [geolocationError], [geolocationOptions]); + + +### Parámetros + +* **geolocationSuccess**: la devolución de llamada que se pasa a la posición actual. + +* **geolocationError**: *(opcional)* la devolución de llamada que se ejecuta si se produce un error. + +* **geolocationOptions**: *(opcional)* las opciones de geolocalización. + +### Ejemplo + + onSuccess Callback / / este método acepta un objeto Position, que contiene el / / coordenadas GPS actual / / var onSuccess = function(position) {alert (' latitud: ' + position.coords.latitude + '\n' + ' longitud: ' + position.coords.longitude + '\n' + ' altitud: ' + position.coords.altitude + '\n' + ' exactitud: ' + position.coords.accuracy + '\n' + ' altitud exactitud: ' + position.coords.altitudeAccuracy + '\n' + ' hacia: ' + position.coords.heading + '\n' + ' velocidad: ' + position.coords.speed + '\n' + ' Timestamp: ' + position.timestamp + '\n');}; + + onError Callback recibe un objeto PositionError / / function onError(error) {alert (' código: ' + error.code + '\n' + ' mensaje: ' + error.message + '\n');} + + navigator.geolocation.getCurrentPosition (onSuccess, onError); + + +## navigator.geolocation.watchPosition + +Devuelve la posición actual del dispositivo cuando se detecta un cambio de posición. Cuando el dispositivo recupera una nueva ubicación, el `geolocationSuccess` devolución de llamada se ejecuta con un `Position` objeto como parámetro. Si hay un error, el `geolocationError` devolución de llamada se ejecuta con un `PositionError` objeto como parámetro. + + var watchId = navigator.geolocation.watchPosition (geolocationSuccess, [geolocationError], [geolocationOptions]); + + +### Parámetros + +* **geolocationSuccess**: la devolución de llamada que se pasa a la posición actual. + +* **geolocationError**: (opcional) la devolución de llamada que se ejecuta si se produce un error. + +* **geolocationOptions**: opciones (opcional) la geolocalización. + +### Devoluciones + +* **Cadena**: devuelve un identificador de reloj que hace referencia el intervalo de posición del reloj. El id del reloj debe ser utilizado con `navigator.geolocation.clearWatch` para dejar de ver a los cambios de posición. + +### Ejemplo + + onSuccess Callback / / este método acepta un objeto 'Position', que contiene / / coordenadas GPS de la corriente / / function onSuccess(position) {var elemento = document.getElementById('geolocation'); + element.innerHTML = ' latitud: ' + position.coords.latitude + ' < br / >' + ' longitud: ' + position.coords.longitude + ' < br / >' + ' < hr / >' + element.innerHTML; + } / / onError Callback recibe un objeto PositionError / / function onError(error) {alert (' código: ' + error.code + '\n' + ' mensaje: ' + error.message + '\n');} + + Opciones: tira un error si no se recibe ninguna actualización cada 30 segundos. + var watchID = navigator.geolocation.watchPosition (onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +Parámetros opcionales para personalizar la recuperación de la geolocalización`Position`. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### Opciones + +* **enableHighAccuracy**: proporciona una pista que la aplicación necesita los mejores resultados posibles. De forma predeterminada, el dispositivo intentará recuperar un `Position` usando métodos basados en red. Al establecer esta propiedad en `true` dice el marco a utilizar métodos más precisos, como el posicionamiento satelital. *(Boolean)* + +* **tiempo de espera**: la longitud máxima de tiempo (en milisegundos) que está permitido el paso de la llamada a `navigator.geolocation.getCurrentPosition` o `geolocation.watchPosition` hasta el correspondiente `geolocationSuccess` devolución de llamada se ejecuta. Si el `geolocationSuccess` no se invoque "callback" dentro de este tiempo, el `geolocationError` devolución de llamada se pasa un `PositionError.TIMEOUT` código de error. (Tenga en cuenta que cuando se utiliza en conjunción con `geolocation.watchPosition` , el `geolocationError` "callback" podría ser llamado en un intervalo cada `timeout` milisegundos!) *(Número)* + +* **maximumAge**: aceptar un puesto en la memoria caché, cuya edad no es mayor que el tiempo especificado en milisegundos. *(Número)* + +### Rarezas Android + +Emuladores Android 2.x no devuelva un resultado de geolocalización a menos que el `enableHighAccuracy` opción se establece en`true`. + +## navigator.geolocation.clearWatch + +Deja de ver cambios en la ubicación del dispositivo al que hace referencia el `watchID` parámetro. + + navigator.geolocation.clearWatch(watchID); + + +### Parámetros + +* **watchID**: el id del intervalo `watchPosition` para despejar. (String) + +### Ejemplo + + Opciones: ver los cambios en la posición y usar más / / exacta posición disponible del método de adquisición. + var watchID = navigator.geolocation.watchPosition (onSuccess, onError, { enableHighAccuracy: true }); + + ... después de... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +Contiene `Position` coordenadas y timestamp, creado por la API de geolocalización. + +### Propiedades + +* **coordenadas**: un conjunto de coordenadas geográficas. *(Coordenadas)* + +* **timestamp**: fecha y hora de creación `coords` . *(DOMTimeStamp)* + +## Coordinates + +A `Coordinates` objeto está unido a un `Position` que está disponible para funciones de retrollamada en las solicitudes para la posición actual del objeto. Contiene un conjunto de propiedades que describen las coordenadas geográficas de posición. + +### Propiedades + +* **Latitude**: latitud en grados decimales. *(Número)* + +* **longitud**: longitud en grados decimales. *(Número)* + +* **altitud**: altura de la posición en metros por encima del elipsoide. *(Número)* + +* **exactitud**: nivel de precisión de las coordenadas de latitud y longitud en metros. *(Número)* + +* **altitudeAccuracy**: nivel de precisión de las coordenadas de altitud en metros. *(Número)* + +* **Dirección**: dirección del recorrido, especificado en grados contando hacia la derecha en relación con el norte verdadero. *(Número)* + +* **velocidad**: velocidad actual del dispositivo especificado en metros por segundo. *(Número)* + +### Amazon fuego OS rarezas + +**altitudeAccuracy**: no compatible con dispositivos Android, regresando`null`. + +### Rarezas Android + +**altitudeAccuracy**: no compatible con dispositivos Android, regresando`null`. + +## PositionError + +El `PositionError` objeto se pasa a la `geolocationError` función de devolución de llamada cuando se produce un error con navigator.geolocation. + +### Propiedades + +* **code**: uno de los códigos de error predefinido enumerados a continuación. + +* **mensaje**: mensaje de Error que describe los detalles del error encontrado. + +### Constantes + +* `PositionError.PERMISSION_DENIED` + * Regresó cuando los usuarios no permiten la aplicación recuperar información de la posición. Esto depende de la plataforma. +* `PositionError.POSITION_UNAVAILABLE` + * Regresó cuando el dispositivo es capaz de recuperar una posición. En general, esto significa que el dispositivo no está conectado a una red o no puede obtener una solución vía satélite. +* `PositionError.TIMEOUT` + * Cuando el dispositivo es capaz de recuperar una posición dentro del tiempo especificado por el `timeout` incluido en `geolocationOptions` . Cuando se utiliza con `navigator.geolocation.watchPosition` , este error podría pasar repetidamente a la `geolocationError` "callback" cada `timeout` milisegundos. diff --git a/plugins/cordova-plugin-geolocation/doc/fr/README.md b/plugins/cordova-plugin-geolocation/doc/fr/README.md new file mode 100644 index 0000000..775a487 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/doc/fr/README.md @@ -0,0 +1,227 @@ + + +# cordova-plugin-geolocation + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-geolocation.svg)](https://travis-ci.org/apache/cordova-plugin-geolocation) + +Ce plugin fournit des informations sur l'emplacement de l'appareil, tels que la latitude et la longitude. Les sources habituelles d'information incluent le Système de Positionnement Global (GPS) et la position déduite de signaux des réseaux tels que l'adresse IP, RFID, les adresses MAC WiFi et Bluetooth et les IDs cellulaires GSM/CDMA. Il n'y a cependant aucune garantie que cette API renvoie la position réelle de l'appareil. + +Cette API est basée sur la [Spécification de l'API Geolocation du W3C](http://dev.w3.org/geo/api/spec-source.html) et s'exécute uniquement sur les appareils qui n'en proposent pas déjà une implémentation. + +**Avertissement**: collecte et utilisation des données de géolocalisation soulève des questions importantes de la vie privée. La politique de confidentialité de votre application devrait traiter de la manière dont l'application utilise les données de géolocalisation, si elle les partage avec d'autres parties ou non et définir le niveau de précision de celles-ci (par exemple grossier, fin, restreint au code postal, etc.). Données de géolocalisation sont généralement considéré comme sensibles car elle peut révéler la localisation de l'utilisateur et, si stocké, l'histoire de leurs voyages. Par conséquent, en plus de la politique de confidentialité de l'application, vous devez envisager fortement fournissant un avis juste-à-temps, avant que l'application accède aux données de géolocalisation (si le système d'exploitation de périphérique n'est pas faire déjà). Cette notice devrait contenir les informations susmentionnées, ainsi que permettre de recueillir l'autorisation de l'utilisateur (par exemple, en offrant les possibilités **OK** et **Non merci**). Pour plus d'informations, veuillez vous référer à la section "Guide du respect de la vie privée". + +Ce plugin définit un global `navigator.geolocation` objet (pour les plateformes où il est autrement manquant). + +Bien que l'objet est dans la portée globale, les fonctions offertes par ce plugin ne sont pas disponibles jusqu'après la `deviceready` événement. + + document.addEventListener (« deviceready », onDeviceReady, false) ; + function onDeviceReady() {console.log ("navigator.geolocation fonctionne bien");} + + +## Installation + +Pour cela, cordova 5.0 + (1.0.0 stable actuelle) + + cordova plugin add cordova-plugin-geolocation + + +Anciennes versions de cordova peuvent toujours installer via l'id obsolète (rassis 0.3.12) + + Cordova plugin ajouter org.apache.cordova.geolocation + + +Il est également possible d'installer directement via l'url de repo (instable) + + cordova plugin add https://github.com/apache/cordova-plugin-geolocation.git + + +## Plates-formes supportées + + * Amazon Fire OS + * Android + * BlackBerry 10 + * Firefox OS + * iOS + * Paciarelli + * Windows Phone 7 et 8 + * Windows 8 + * Windows + +## Méthodes + + * navigator.geolocation.getCurrentPosition + * navigator.geolocation.watchPosition + * navigator.geolocation.clearWatch + +## Objets (lecture seule) + + * Position + * PositionError + * Coordonnées + +## navigator.geolocation.getCurrentPosition + +Retourne la position actuelle de l'appareil à la `geolocationSuccess` rappel avec un `Position` objet comme paramètre. Si une erreur se produit, le `geolocationError` rappel est passé un `PositionError` objet. + + navigator.geolocation.getCurrentPosition (geolocationSuccess, [geolocationError], [geolocationOptions]) ; + + +### Paramètres + + * **geolocationSuccess** : la fonction callback à laquelle est transmise la position actuelle. + + * **geolocationError** : *(facultative)* la fonction callback s'exécutant si une erreur survient. + + * **geolocationOptions** : *(facultatives)* des préférences de géolocalisation. + +### Exemple + + onSuccess rappel / / cette méthode accepte un objet de Position, qui contient le / / coordonnées GPS actuel / / var onSuccess = function(position) {alert ('Latitude: ' + position.coords.latitude + « \n » + ' Longitude: ' + position.coords.longitude + « \n » + ' Altitude: ' + position.coords.altitude + « \n » + ' précision: ' + position.coords.accuracy + « \n » + ' Altitude précision: ' + position.coords.altitudeAccuracy + « \n » + ' rubrique: ' + position.coords.heading + « \n » + ' vitesse: ' + position.coords.speed + « \n » + ' Timestamp: ' + position.timestamp + « \n »);} ; + + onError rappel reçoit un objet PositionError / / function onError(error) {alert ('code: "+ error.code + « \n » + ' message: ' + error.message + « \n »);} + + navigator.geolocation.getCurrentPosition (onSuccess, onError) ; + + +## navigator.geolocation.watchPosition + +Retourne la position actuelle de l'appareil lorsqu'un changement de position est détecté. Lorsque l'appareil récupère un nouvel emplacement, le `geolocationSuccess` rappel s'exécute avec un `Position` objet comme paramètre. Si une erreur se produit, le `geolocationError` rappel s'exécute avec un `PositionError` objet comme paramètre. + + var watchId = navigator.geolocation.watchPosition (geolocationSuccess, [geolocationError], [geolocationOptions]) ; + + +### Paramètres + + * **geolocationSuccess** : la fonction callback à laquelle est transmise la position actuelle. + + * **geolocationError** : (facultative) la fonction callback s'exécutant lorsqu'une erreur survient. + + * **geolocationOptions** : (facultatives) options de personnalisation de la géolocalisation. + +### Retours + + * **Chaîne**: retourne un id de montre qui fait référence à l'intervalle de position montre. L'id de la montre doit être utilisé avec `navigator.geolocation.clearWatch` d'arrêter de regarder pour les changements de position. + +### Exemple + + onSuccess rappel / / cette méthode accepte un objet « Position », qui contient / / coordonnées de GPS le courant / / function onSuccess(position) {var element = document.getElementById('geolocation') ; + element.innerHTML = ' Latitude: "+ position.coords.latitude + ' < br / >' + ' Longitude:" + position.coords.longitude + ' < br / >' + ' < hr / >' + element.innerHTML ; + } / / onError rappel reçoit un objet PositionError / / function onError(error) {alert ('code: ' + error.code + « \n » + "message: ' + error.message + « \n »);} + + Options : lever une erreur si aucune mise à jour n'est reçu toutes les 30 secondes. + var watchID = navigator.geolocation.watchPosition (onSuccess, onError, { timeout: 30000 }) ; + + +## geolocationOptions + +Paramètres optionnels pour personnaliser la récupération de la géolocalisation`Position`. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true } ; + + +### Options + + * **enableHighAccuracy** : indique que l'application nécessite les meilleurs résultats possibles. Par défaut, l'appareil tente de récupérer une `Position` à l'aide de méthodes basées sur le réseau. Définir cette propriété à `true` demande à Cordova d'utiliser des méthodes plus précises, telles que la localisation par satellite. *(Boolean)* + + * **délai d'attente**: la longueur maximale de temps (en millisecondes) qui peut passer de l'appel à `navigator.geolocation.getCurrentPosition` ou `geolocation.watchPosition` jusqu'à ce que le correspondant `geolocationSuccess` rappel s'exécute. Si `geolocationSuccess` n'est pas appelée dans ce délai, le code d'erreur `PositionError.TIMEOUT` est transmis à la fonction callback `geolocationError`. (Notez que, dans le cas de `geolocation.watchPosition`, la fonction callback `geolocationError` pourrait être appelée à un intervalle régulier de `timeout` millisecondes !) *(Number)* + + * **maximumAge** : accepter une position mise en cache dont l'âge ne dépasse pas le délai spécifié en millisecondes. *(Number)* + +### Quirks Android + +Émulateurs Android 2.x ne pas retournent un résultat de géolocalisation, à moins que le `enableHighAccuracy` option est définie sur`true`. + +## navigator.geolocation.clearWatch + +Arrêter de regarder pour les modifications à l'emplacement de l'appareil référencé par le `watchID` paramètre. + + navigator.geolocation.clearWatch(watchID) ; + + +### Paramètres + + * **watchID** : l'identifiant de l'intervalle `watchPosition` à effacer. (String) + +### Exemple + + Options : suivi des modifications dans la position et utilise le plus / / exacte position méthode d'acquisition disponible. + var watchID = navigator.geolocation.watchPosition (onSuccess, onError, { enableHighAccuracy: true }) ; + + .. plus sur... + + navigator.geolocation.clearWatch(watchID) ; + + +## Position + +Contient `Position` coordonnées et timestamp, créé par l'API de géolocalisation. + +### Propriétés + + * **coords** : un ensemble de coordonnées géographiques. *(Coordinates)* + + * **timestamp** : horodatage de la création de `coords`. *(DOMTimeStamp)* + +## Coordonnées + +A `Coordinates` objet est attaché à un `Position` objet qui n'existe pas de fonctions de rappel dans les requêtes pour la position actuelle. Il contient un ensemble de propriétés qui décrivent les coordonnées géographiques d'une position. + +### Propriétés + + * **latitude** : latitude en degrés décimaux. *(Number)* + + * **longitude** : longitude en degrés décimaux. *(Number)* + + * **altitude** : hauteur de la position en mètres au-dessus de l'ellipsoïde. *(Number)* + + * **accuracy** : niveau de précision des valeurs de latitude et longitude, en mètres. *(Number)* + + * **altitudeAccuracy** : niveau de précision de la valeur d'altitude, en mètres. *(Number)* + + * **heading** : direction du trajet, indiquée en degrés comptés dans le sens horaire par rapport au vrai Nord. *(Number)* + + * **speed** : vitesse au sol actuelle de l'appareil, indiquée en mètres par seconde. *(Number)* + +### Amazon Fire OS Quirks + +**altitudeAccuracy**: ne pas pris en charge par les appareils Android, retour`null`. + +### Quirks Android + +**altitudeAccuracy**: ne pas pris en charge par les appareils Android, retour`null`. + +## PositionError + +Le `PositionError` objet est passé à la `geolocationError` fonction de rappel lorsqu'une erreur se produit avec navigator.geolocation. + +### Propriétés + + * **code**: l'un des codes d'erreur prédéfinis énumérés ci-dessous. + + * **message** : un message d'erreur détaillant l'erreur rencontrée. + +### Constantes + + * `PositionError.PERMISSION_DENIED` + * Retourné lorsque les utilisateurs ne permettent pas l'application extraire des informations de position. Cela dépend de la plate-forme. + * `PositionError.POSITION_UNAVAILABLE` + * Retourné lorsque le périphérique n'est pas en mesure de récupérer une position. En général, cela signifie que l'appareil n'est pas connecté à un réseau ou ne peut pas obtenir un correctif de satellite. + * `PositionError.TIMEOUT` + * Retourné lorsque le périphérique n'est pas en mesure de récupérer une position dans le délai précisé par le `timeout` inclus dans `geolocationOptions` . Lorsqu'il est utilisé avec `navigator.geolocation.watchPosition` , cette erreur pourrait être transmise à plusieurs reprises à la `geolocationError` rappel chaque `timeout` millisecondes. \ No newline at end of file diff --git a/plugins/cordova-plugin-geolocation/doc/fr/index.md b/plugins/cordova-plugin-geolocation/doc/fr/index.md new file mode 100644 index 0000000..4d48637 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/doc/fr/index.md @@ -0,0 +1,214 @@ + + +# cordova-plugin-geolocation + +Ce plugin fournit des informations sur l'emplacement de l'appareil, tels que la latitude et la longitude. Les sources habituelles d'information incluent le Système de Positionnement Global (GPS) et la position déduite de signaux des réseaux tels que l'adresse IP, RFID, les adresses MAC WiFi et Bluetooth et les IDs cellulaires GSM/CDMA. Il n'y a cependant aucune garantie que cette API renvoie la position réelle de l'appareil. + +Cette API est basée sur la [Spécification de l'API Geolocation du W3C][1] et s'exécute uniquement sur les appareils qui n'en proposent pas déjà une implémentation. + + [1]: http://dev.w3.org/geo/api/spec-source.html + +**Avertissement**: collecte et utilisation des données de géolocalisation soulève des questions importantes de la vie privée. La politique de confidentialité de votre application devrait traiter de la manière dont l'application utilise les données de géolocalisation, si elle les partage avec d'autres parties ou non et définir le niveau de précision de celles-ci (par exemple grossier, fin, restreint au code postal, etc.). Données de géolocalisation sont généralement considéré comme sensibles car elle peut révéler la localisation de l'utilisateur et, si stocké, l'histoire de leurs voyages. Par conséquent, en plus de la politique de confidentialité de l'application, vous devez envisager fortement fournissant un avis juste-à-temps, avant que l'application accède aux données de géolocalisation (si le système d'exploitation de périphérique n'est pas faire déjà). Cette notice devrait contenir les informations susmentionnées, ainsi que permettre de recueillir l'autorisation de l'utilisateur (par exemple, en offrant les possibilités **OK** et **Non merci**). Pour plus d'informations, veuillez vous référer à la section "Guide du respect de la vie privée". + +Ce plugin définit un global `navigator.geolocation` objet (pour les plateformes où il est autrement manquant). + +Bien que l'objet est dans la portée globale, les fonctions offertes par ce plugin ne sont pas disponibles jusqu'après la `deviceready` événement. + + document.addEventListener (« deviceready », onDeviceReady, false) ; + function onDeviceReady() {console.log ("navigator.geolocation fonctionne bien");} + + +## Installation + + Cordova plugin ajouter cordova-plugin-geolocation + + +## Plates-formes prises en charge + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Paciarelli +* Windows Phone 7 et 8 +* Windows 8 + +## Méthodes + +* navigator.geolocation.getCurrentPosition +* navigator.geolocation.watchPosition +* navigator.geolocation.clearWatch + +## Objets (lecture seule) + +* Position +* PositionError +* Coordonnées + +## navigator.geolocation.getCurrentPosition + +Retourne la position actuelle de l'appareil à la `geolocationSuccess` rappel avec un `Position` objet comme paramètre. Si une erreur se produit, le `geolocationError` rappel est passé un `PositionError` objet. + + navigator.geolocation.getCurrentPosition (geolocationSuccess, [geolocationError], [geolocationOptions]) ; + + +### Paramètres + +* **geolocationSuccess** : la fonction callback à laquelle est transmise la position actuelle. + +* **geolocationError** : *(facultative)* la fonction callback s'exécutant si une erreur survient. + +* **geolocationOptions** : *(facultatives)* des préférences de géolocalisation. + +### Exemple + + onSuccess rappel / / cette méthode accepte un objet de Position, qui contient le / / coordonnées GPS actuel / / var onSuccess = function(position) {alert ('Latitude: ' + position.coords.latitude + « \n » + ' Longitude: ' + position.coords.longitude + « \n » + ' Altitude: ' + position.coords.altitude + « \n » + ' précision: ' + position.coords.accuracy + « \n » + ' Altitude précision: ' + position.coords.altitudeAccuracy + « \n » + ' rubrique: ' + position.coords.heading + « \n » + ' vitesse: ' + position.coords.speed + « \n » + ' Timestamp: ' + position.timestamp + « \n »);} ; + + onError rappel reçoit un objet PositionError / / function onError(error) {alert ('code: "+ error.code + « \n » + ' message: ' + error.message + « \n »);} + + navigator.geolocation.getCurrentPosition (onSuccess, onError) ; + + +## navigator.geolocation.watchPosition + +Retourne la position actuelle de l'appareil lorsqu'un changement de position est détecté. Lorsque l'appareil récupère un nouvel emplacement, le `geolocationSuccess` rappel s'exécute avec un `Position` objet comme paramètre. Si une erreur se produit, le `geolocationError` rappel s'exécute avec un `PositionError` objet comme paramètre. + + var watchId = navigator.geolocation.watchPosition (geolocationSuccess, [geolocationError], [geolocationOptions]) ; + + +### Paramètres + +* **geolocationSuccess**: la fonction de rappel qui est passée de la position actuelle. + +* **geolocationError** : (facultative) la fonction callback s'exécutant lorsqu'une erreur survient. + +* **geolocationOptions** : (facultatives) options de personnalisation de la géolocalisation. + +### Retours + +* **Chaîne**: retourne un id de montre qui fait référence à l'intervalle de position montre. L'id de la montre doit être utilisé avec `navigator.geolocation.clearWatch` d'arrêter de regarder pour les changements de position. + +### Exemple + + onSuccess rappel / / cette méthode accepte un objet « Position », qui contient / / coordonnées de GPS le courant / / function onSuccess(position) {var element = document.getElementById('geolocation') ; + element.innerHTML = ' Latitude: "+ position.coords.latitude + ' < br / >' + ' Longitude:" + position.coords.longitude + ' < br / >' + ' < hr / >' + element.innerHTML ; + } / / onError rappel reçoit un objet PositionError / / function onError(error) {alert ('code: ' + error.code + « \n » + "message: ' + error.message + « \n »);} + + Options : lever une erreur si aucune mise à jour n'est reçu toutes les 30 secondes. + var watchID = navigator.geolocation.watchPosition (onSuccess, onError, { timeout: 30000 }) ; + + +## geolocationOptions + +Paramètres optionnels pour personnaliser la récupération de la géolocalisation`Position`. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true } ; + + +### Options + +* **enableHighAccuracy** : indique que l'application nécessite les meilleurs résultats possibles. Par défaut, l'appareil tente de récupérer une `Position` à l'aide de méthodes basées sur le réseau. Définir cette propriété à `true` demande à Cordova d'utiliser des méthodes plus précises, telles que la localisation par satellite. *(Boolean)* + +* **délai d'attente**: la longueur maximale de temps (en millisecondes) qui peut passer de l'appel à `navigator.geolocation.getCurrentPosition` ou `geolocation.watchPosition` jusqu'à ce que le correspondant `geolocationSuccess` rappel s'exécute. Si `geolocationSuccess` n'est pas appelée dans ce délai, le code d'erreur `PositionError.TIMEOUT` est transmis à la fonction callback `geolocationError`. (Notez que, dans le cas de `geolocation.watchPosition`, la fonction callback `geolocationError` pourrait être appelée à un intervalle régulier de `timeout` millisecondes !) *(Number)* + +* **maximumAge** : accepter une position mise en cache dont l'âge ne dépasse pas le délai spécifié en millisecondes. *(Number)* + +### Quirks Android + +Émulateurs Android 2.x ne pas retournent un résultat de géolocalisation, à moins que le `enableHighAccuracy` option est définie sur`true`. + +## navigator.geolocation.clearWatch + +Arrêter de regarder pour les modifications à l'emplacement de l'appareil référencé par le `watchID` paramètre. + + navigator.geolocation.clearWatch(watchID) ; + + +### Paramètres + +* **watchID** : l'identifiant de l'intervalle `watchPosition` à effacer. (String) + +### Exemple + + Options : suivi des modifications dans la position et utilise le plus / / exacte position méthode d'acquisition disponible. + var watchID = navigator.geolocation.watchPosition (onSuccess, onError, { enableHighAccuracy: true }) ; + + .. plus sur... + + navigator.geolocation.clearWatch(watchID) ; + + +## Position + +Contient `Position` coordonnées et timestamp, créé par l'API de géolocalisation. + +### Propriétés + +* **coords** : un ensemble de coordonnées géographiques. *(Coordinates)* + +* **timestamp** : horodatage de la création de `coords`. *(DOMTimeStamp)* + +## Coordonnées + +A `Coordinates` objet est attaché à un `Position` objet qui n'existe pas de fonctions de rappel dans les requêtes pour la position actuelle. Il contient un ensemble de propriétés qui décrivent les coordonnées géographiques d'une position. + +### Propriétés + +* **latitude** : latitude en degrés décimaux. *(Number)* + +* **longitude** : longitude en degrés décimaux. *(Number)* + +* **altitude** : hauteur de la position en mètres au-dessus de l'ellipsoïde. *(Number)* + +* **accuracy** : niveau de précision des valeurs de latitude et longitude, en mètres. *(Number)* + +* **altitudeAccuracy** : niveau de précision de la valeur d'altitude, en mètres. *(Number)* + +* **heading** : direction du trajet, indiquée en degrés comptés dans le sens horaire par rapport au vrai Nord. *(Number)* + +* **speed** : vitesse au sol actuelle de l'appareil, indiquée en mètres par seconde. *(Number)* + +### Amazon Fire OS Quirks + +**altitudeAccuracy**: ne pas pris en charge par les appareils Android, retour`null`. + +### Quirks Android + +**altitudeAccuracy**: ne pas pris en charge par les appareils Android, retour`null`. + +## PositionError + +Le `PositionError` objet est passé à la `geolocationError` fonction de rappel lorsqu'une erreur se produit avec navigator.geolocation. + +### Propriétés + +* **code**: l'un des codes d'erreur prédéfinis énumérés ci-dessous. + +* **message** : un message d'erreur détaillant l'erreur rencontrée. + +### Constantes + +* `PositionError.PERMISSION_DENIED` + * Retourné lorsque les utilisateurs ne permettent pas l'application extraire des informations de position. Cela dépend de la plate-forme. +* `PositionError.POSITION_UNAVAILABLE` + * Retourné lorsque le périphérique n'est pas en mesure de récupérer une position. En général, cela signifie que l'appareil n'est pas connecté à un réseau ou ne peut pas obtenir un correctif de satellite. +* `PositionError.TIMEOUT` + * Retourné lorsque le périphérique n'est pas en mesure de récupérer une position dans le délai précisé par le `timeout` inclus dans `geolocationOptions` . Lorsqu'il est utilisé avec `navigator.geolocation.watchPosition` , cette erreur pourrait être transmise à plusieurs reprises à la `geolocationError` rappel chaque `timeout` millisecondes. diff --git a/plugins/cordova-plugin-geolocation/doc/it/README.md b/plugins/cordova-plugin-geolocation/doc/it/README.md new file mode 100644 index 0000000..ffa472b --- /dev/null +++ b/plugins/cordova-plugin-geolocation/doc/it/README.md @@ -0,0 +1,268 @@ + + +# cordova-plugin-geolocation + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-geolocation.svg)](https://travis-ci.org/apache/cordova-plugin-geolocation) + +Questo plugin fornisce informazioni sulla posizione del dispositivo, come latitudine e longitudine. Comuni fonti di informazioni sulla posizione comprendono Global Positioning System (GPS) e posizione dedotta dai segnali di rete come indirizzo IP, indirizzi, RFID, WiFi e Bluetooth MAC e cellulare GSM/CDMA IDs. Non non c'è alcuna garanzia che l'API restituisce la posizione effettiva del dispositivo. + +Questa API è basata sulla [Specifica di W3C Geolocation API](http://dev.w3.org/geo/api/spec-source.html)e viene eseguito solo su dispositivi che non già forniscono un'implementazione. + +**Avviso**: raccolta e utilizzo dei dati di geolocalizzazione solleva questioni di privacy importante. Politica sulla privacy dell'app dovrebbe discutere come app utilizza dati di geolocalizzazione, se è condiviso con altre parti e il livello di precisione dei dati (ad esempio, Cap grossolana, fine, livello, ecc.). Dati di geolocalizzazione sono generalmente considerati sensibili perché può rivelare la sorte dell'utente e, se conservati, la storia dei loro viaggi. Pertanto, oltre alla politica di privacy dell'app, è fortemente consigliabile fornendo un preavviso di just-in-time prima app accede ai dati di geolocalizzazione (se il sistema operativo del dispositivo non farlo già). Tale comunicazione deve fornire le informazioni stesse notate sopra, oltre ad ottenere l'autorizzazione (ad esempio, presentando scelte per **OK** e **No grazie**). Per ulteriori informazioni, vedere la guida sulla Privacy. + +Questo plugin definisce un oggetto globale `navigator.geolocation` (per le piattaforme dove altrimenti è manca). + +Sebbene l'oggetto sia in ambito globale, funzionalità fornite da questo plugin non sono disponibili fino a dopo l'evento `deviceready`. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + + +## Installazione + +Ciò richiede cordova 5.0 + (attuale stabile 1.0.0) + + cordova plugin add cordova-plugin-geolocation + + +Versioni precedenti di cordova comunque possono installare tramite l'id deprecata (stantio 0.3.12) + + cordova plugin add org.apache.cordova.geolocation + + +È anche possibile installare direttamente tramite url di repo (instabile) + + cordova plugin add https://github.com/apache/cordova-plugin-geolocation.git + + +## Piattaforme supportate + + * Amazon fuoco OS + * Android + * BlackBerry 10 + * Firefox OS + * iOS + * Tizen + * Windows Phone 7 e 8 + * Windows 8 + * Windows + +## Metodi + + * navigator.geolocation.getCurrentPosition + * navigator.geolocation.watchPosition + * navigator.geolocation.clearWatch + +## Oggetti (sola lettura) + + * Position + * PositionError + * Coordinates + +## navigator.geolocation.getCurrentPosition + +Restituisce la posizione corrente del dispositivo il callback di `geolocationSuccess` con un `Position` di oggetto come parametro. Se c'è un errore, `geolocationError` callback viene passato un oggetto `PositionError`. + + navigator.geolocation.getCurrentPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### Parametri + + * **geolocationSuccess**: il callback passato alla posizione corrente. + + * **geolocationError**: *(facoltativo)* il callback che viene eseguito se si verifica un errore. + + * **geolocationOptions**: *(opzionale)* le opzioni di geolocalizzazione. + +### Esempio + + // 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'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + + +## navigator.geolocation.watchPosition + +Restituisce la posizione corrente del dispositivo quando viene rilevata una modifica della posizione. Quando il dispositivo recupera una nuova posizione, il callback `geolocationSuccess` esegue con un `Position` di oggetto come parametro. Se c'è un errore, `geolocationError` callback viene eseguito con un oggetto `PositionError` come parametro. + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### Parametri + + * **geolocationSuccess**: il callback passato alla posizione corrente. + + * **geolocationError**: (facoltativo) il callback che viene eseguito se si verifica un errore. + + * **geolocationOptions**: opzioni (opzionale) la geolocalizzazione. + +### Restituisce + + * **Stringa**: restituisce un id di orologio che fa riferimento l'intervallo di posizione orologio. L'id dell'orologio deve essere usato con `navigator.geolocation.clearWatch` a smettere di guardare per cambiamenti di posizione. + +### Esempio + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '
' + + 'Longitude: ' + position.coords.longitude + '
' + + '
' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +Parametri opzionali per personalizzare il recupero di geolocalizzazione `Position`. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### Opzioni + + * **enableHighAccuracy**: fornisce un suggerimento che l'applicazione ha bisogno i migliori risultati possibili. Per impostazione predefinita, il dispositivo tenta di recuperare un `Position` usando metodi basati sulla rete. Impostando questa proprietà su `true` indica al framework di utilizzare metodi più accurati, come posizionamento satellitare. *(Boolean)* + + * **timeout**: la lunghezza massima di tempo (in millisecondi) che è consentito per passare dalla chiamata a `navigator.geolocation.getCurrentPosition` o `geolocation.watchPosition` fino a quando il corrispondente `geolocationSuccess` callback viene eseguito. Se il `geolocationSuccess` callback non viene richiamato entro questo tempo, il `geolocationError` callback viene passata una `PositionError.TIMEOUT` codice di errore. (Si noti che, quando utilizzato in combinazione con `geolocation.watchPosition` , il `geolocationError` callback potrebbe essere chiamato un intervallo ogni `timeout` millisecondi!) *(Numero)* + + * **maximumAge**: accettare una posizione memorizzata nella cache in cui età è minore il tempo specificato in millisecondi. *(Numero)* + +### Stranezze Android + +Emulatori Android 2. x non restituiscono un risultato di geolocalizzazione a meno che l'opzione `enableHighAccuracy` è impostata su `true`. + +## navigator.geolocation.clearWatch + +Smettere di guardare per le modifiche alla posizione del dispositivo a cui fa riferimento il parametro `watchID`. + + navigator.geolocation.clearWatch(watchID); + + +### Parametri + + * **watchID**: l'id del `watchPosition` intervallo per cancellare. (String) + +### Esempio + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +Contiene le coordinate della `Position` e timestamp, creato da geolocation API. + +### Proprietà + + * **CoOrds**: un insieme di coordinate geografiche. *(Coordinate)* + + * **timestamp**: timestamp di creazione per `coords` . *(DOMTimeStamp)* + +## Coordinates + +Un oggetto `Coordinates` è associato a un oggetto `Position` disponibile per le funzioni di callback in richieste per la posizione corrente. Contiene un insieme di proprietà che descrivono le coordinate geografiche di una posizione. + +### Proprietà + + * **latitudine**: latitudine in gradi decimali. *(Numero)* + + * **longitudine**: longitudine in gradi decimali. *(Numero)* + + * **altitudine**: altezza della posizione in metri sopra l'ellissoide. *(Numero)* + + * **accuratezza**: livello di accuratezza delle coordinate latitudine e longitudine in metri. *(Numero)* + + * **altitudeAccuracy**: livello di accuratezza della coordinata altitudine in metri. *(Numero)* + + * **rubrica**: senso di marcia, specificata in gradi in senso orario rispetto al vero nord di conteggio. *(Numero)* + + * **velocità**: velocità attuale terra del dispositivo, specificato in metri al secondo. *(Numero)* + +### Amazon fuoco OS stranezze + +**altitudeAccuracy**: non supportato dai dispositivi Android, restituendo `null`. + +### Stranezze Android + +**altitudeAccuracy**: non supportato dai dispositivi Android, restituendo `null`. + +## PositionError + +L'oggetto `PositionError` viene passato alla funzione di callback `geolocationError` quando si verifica un errore con navigator.geolocation. + +### Proprietà + + * **codice**: uno dei codici di errore predefiniti elencati di seguito. + + * **messaggio**: messaggio di errore che descrive i dettagli dell'errore rilevato. + +### Costanti + + * `PositionError.PERMISSION_DENIED` + * Restituito quando gli utenti non consentono l'applicazione recuperare le informazioni di posizione. Questo è dipendente dalla piattaforma. + * `PositionError.POSITION_UNAVAILABLE` + * Restituito quando il dispositivo è in grado di recuperare una posizione. In generale, questo significa che il dispositivo non è connesso a una rete o non può ottenere un fix satellitare. + * `PositionError.TIMEOUT` + * Restituito quando il dispositivo è in grado di recuperare una posizione entro il tempo specificato dal `timeout` incluso `geolocationOptions` . Quando utilizzato con `navigator.geolocation.watchPosition` , questo errore potrebbe essere passato più volte per la `geolocationError` richiamata ogni `timeout` millisecondi. \ No newline at end of file diff --git a/plugins/cordova-plugin-geolocation/doc/it/index.md b/plugins/cordova-plugin-geolocation/doc/it/index.md new file mode 100644 index 0000000..7ba7c5c --- /dev/null +++ b/plugins/cordova-plugin-geolocation/doc/it/index.md @@ -0,0 +1,255 @@ + + +# cordova-plugin-geolocation + +Questo plugin fornisce informazioni sulla posizione del dispositivo, come latitudine e longitudine. Comuni fonti di informazioni sulla posizione comprendono Global Positioning System (GPS) e posizione dedotta dai segnali di rete come indirizzo IP, indirizzi, RFID, WiFi e Bluetooth MAC e cellulare GSM/CDMA IDs. Non non c'è alcuna garanzia che l'API restituisce la posizione effettiva del dispositivo. + +Questa API è basata sulla [Specifica di W3C Geolocation API][1]e viene eseguito solo su dispositivi che non già forniscono un'implementazione. + + [1]: http://dev.w3.org/geo/api/spec-source.html + +**Avviso**: raccolta e utilizzo dei dati di geolocalizzazione solleva questioni di privacy importante. Politica sulla privacy dell'app dovrebbe discutere come app utilizza dati di geolocalizzazione, se è condiviso con altre parti e il livello di precisione dei dati (ad esempio, Cap grossolana, fine, livello, ecc.). Dati di geolocalizzazione sono generalmente considerati sensibili perché può rivelare la sorte dell'utente e, se conservati, la storia dei loro viaggi. Pertanto, oltre alla politica di privacy dell'app, è fortemente consigliabile fornendo un preavviso di just-in-time prima app accede ai dati di geolocalizzazione (se il sistema operativo del dispositivo non farlo già). Tale comunicazione deve fornire le informazioni stesse notate sopra, oltre ad ottenere l'autorizzazione (ad esempio, presentando scelte per **OK** e **No grazie**). Per ulteriori informazioni, vedere la guida sulla Privacy. + +Questo plugin definisce un oggetto globale `navigator.geolocation` (per le piattaforme dove altrimenti è manca). + +Sebbene l'oggetto sia in ambito globale, funzionalità fornite da questo plugin non sono disponibili fino a dopo l'evento `deviceready`. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + + +## Installazione + + cordova plugin add cordova-plugin-geolocation + + +## Piattaforme supportate + +* Amazon fuoco OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 e 8 +* Windows 8 + +## Metodi + +* navigator.geolocation.getCurrentPosition +* navigator.geolocation.watchPosition +* navigator.geolocation.clearWatch + +## Oggetti (sola lettura) + +* Position +* PositionError +* Coordinates + +## navigator.geolocation.getCurrentPosition + +Restituisce la posizione corrente del dispositivo il callback di `geolocationSuccess` con un `Position` di oggetto come parametro. Se c'è un errore, `geolocationError` callback viene passato un oggetto `PositionError`. + + navigator.geolocation.getCurrentPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### Parametri + +* **geolocationSuccess**: il callback passato alla posizione corrente. + +* **geolocationError**: *(facoltativo)* il callback che viene eseguito se si verifica un errore. + +* **geolocationOptions**: *(opzionale)* le opzioni di geolocalizzazione. + +### Esempio + + // 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'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + + +## navigator.geolocation.watchPosition + +Restituisce la posizione corrente del dispositivo quando viene rilevata una modifica della posizione. Quando il dispositivo recupera una nuova posizione, il callback `geolocationSuccess` esegue con un `Position` di oggetto come parametro. Se c'è un errore, `geolocationError` callback viene eseguito con un oggetto `PositionError` come parametro. + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### Parametri + +* **geolocationSuccess**: il callback passato alla posizione corrente. + +* **geolocationError**: (facoltativo) il callback che viene eseguito se si verifica un errore. + +* **geolocationOptions**: opzioni (opzionale) la geolocalizzazione. + +### Restituisce + +* **Stringa**: restituisce un id di orologio che fa riferimento l'intervallo di posizione orologio. L'id dell'orologio deve essere usato con `navigator.geolocation.clearWatch` a smettere di guardare per cambiamenti di posizione. + +### Esempio + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '
' + + 'Longitude: ' + position.coords.longitude + '
' + + '
' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +Parametri opzionali per personalizzare il recupero di geolocalizzazione `Position`. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### Opzioni + +* **enableHighAccuracy**: fornisce un suggerimento che l'applicazione ha bisogno i migliori risultati possibili. Per impostazione predefinita, il dispositivo tenta di recuperare un `Position` usando metodi basati sulla rete. Impostando questa proprietà su `true` indica al framework di utilizzare metodi più accurati, come posizionamento satellitare. *(Boolean)* + +* **timeout**: la lunghezza massima di tempo (in millisecondi) che è consentito per passare dalla chiamata a `navigator.geolocation.getCurrentPosition` o `geolocation.watchPosition` fino a quando il corrispondente `geolocationSuccess` callback viene eseguito. Se il `geolocationSuccess` callback non viene richiamato entro questo tempo, il `geolocationError` callback viene passata una `PositionError.TIMEOUT` codice di errore. (Si noti che, quando utilizzato in combinazione con `geolocation.watchPosition` , il `geolocationError` callback potrebbe essere chiamato un intervallo ogni `timeout` millisecondi!) *(Numero)* + +* **maximumAge**: accettare una posizione memorizzata nella cache in cui età è minore il tempo specificato in millisecondi. *(Numero)* + +### Stranezze Android + +Emulatori Android 2. x non restituiscono un risultato di geolocalizzazione a meno che l'opzione `enableHighAccuracy` è impostata su `true`. + +## navigator.geolocation.clearWatch + +Smettere di guardare per le modifiche alla posizione del dispositivo a cui fa riferimento il parametro `watchID`. + + navigator.geolocation.clearWatch(watchID); + + +### Parametri + +* **watchID**: l'id del `watchPosition` intervallo per cancellare. (String) + +### Esempio + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +Contiene le coordinate della `Position` e timestamp, creato da geolocation API. + +### Proprietà + +* **CoOrds**: un insieme di coordinate geografiche. *(Coordinate)* + +* **timestamp**: timestamp di creazione per `coords` . *(DOMTimeStamp)* + +## Coordinates + +Un oggetto `Coordinates` è associato a un oggetto `Position` disponibile per le funzioni di callback in richieste per la posizione corrente. Contiene un insieme di proprietà che descrivono le coordinate geografiche di una posizione. + +### Proprietà + +* **latitudine**: latitudine in gradi decimali. *(Numero)* + +* **longitudine**: longitudine in gradi decimali. *(Numero)* + +* **altitudine**: altezza della posizione in metri sopra l'ellissoide. *(Numero)* + +* **accuratezza**: livello di accuratezza delle coordinate latitudine e longitudine in metri. *(Numero)* + +* **altitudeAccuracy**: livello di accuratezza della coordinata altitudine in metri. *(Numero)* + +* **rubrica**: senso di marcia, specificata in gradi in senso orario rispetto al vero nord di conteggio. *(Numero)* + +* **velocità**: velocità attuale terra del dispositivo, specificato in metri al secondo. *(Numero)* + +### Amazon fuoco OS stranezze + +**altitudeAccuracy**: non supportato dai dispositivi Android, restituendo `null`. + +### Stranezze Android + +**altitudeAccuracy**: non supportato dai dispositivi Android, restituendo `null`. + +## PositionError + +L'oggetto `PositionError` viene passato alla funzione di callback `geolocationError` quando si verifica un errore con navigator.geolocation. + +### Proprietà + +* **codice**: uno dei codici di errore predefiniti elencati di seguito. + +* **messaggio**: messaggio di errore che descrive i dettagli dell'errore rilevato. + +### Costanti + +* `PositionError.PERMISSION_DENIED` + * Restituito quando gli utenti non consentono l'applicazione recuperare le informazioni di posizione. Questo è dipendente dalla piattaforma. +* `PositionError.POSITION_UNAVAILABLE` + * Restituito quando il dispositivo è in grado di recuperare una posizione. In generale, questo significa che il dispositivo non è connesso a una rete o non può ottenere un fix satellitare. +* `PositionError.TIMEOUT` + * Restituito quando il dispositivo è in grado di recuperare una posizione entro il tempo specificato dal `timeout` incluso `geolocationOptions` . Quando utilizzato con `navigator.geolocation.watchPosition` , questo errore potrebbe essere passato più volte per la `geolocationError` richiamata ogni `timeout` millisecondi. diff --git a/plugins/cordova-plugin-geolocation/doc/ja/README.md b/plugins/cordova-plugin-geolocation/doc/ja/README.md new file mode 100644 index 0000000..59c5ed6 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/doc/ja/README.md @@ -0,0 +1,268 @@ + + +# cordova-plugin-geolocation + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-geolocation.svg)](https://travis-ci.org/apache/cordova-plugin-geolocation) + +このプラグインは緯度や経度などのデバイスの場所に関する情報を提供します。 位置情報の共通のソースはグローバル ポジショニング システム (GPS) と IP アドレス、RFID、WiFi および Bluetooth の MAC アドレス、および GSM/cdma 方式携帯 Id などのネットワーク信号から推定される場所にもあります。 API は、デバイスの実際の場所を返すことの保証はありません。 + +この API は[W3C 地理位置情報 API 仕様](http://dev.w3.org/geo/api/spec-source.html)に基づいており、既に実装を提供しないデバイス上のみで実行します。 + +**警告**: 地理位置情報データの収集と利用を重要なプライバシーの問題を発生させます。 アプリのプライバシー ポリシーは他の当事者とデータ (たとえば、粗い、罰金、郵便番号レベル、等) の精度のレベルでは共有されているかどうか、アプリが地理位置情報データを使用する方法を議論すべきです。 地理位置情報データと一般に見なされる敏感なユーザーの居場所を開示することができますので、彼らの旅行の歴史保存されている場合。 したがって、アプリのプライバシー ポリシーに加えて、強くする必要があります (デバイス オペレーティング システムしない場合そう既に)、アプリケーションに地理位置情報データをアクセスする前に - 時間のお知らせを提供します。 その通知は、上記の (例えば、 **[ok]**を**おかげで**選択肢を提示する) によってユーザーのアクセス許可を取得するだけでなく、同じ情報を提供する必要があります。 詳細については、プライバシーに関するガイドを参照してください。 + +このプラグインは、グローバル `navigator.geolocation` オブジェクト (プラットフォーム行方不明ですそれ以外の場合) を定義します。 + +オブジェクトは、グローバル スコープでですが、このプラグインによって提供される機能は、`deviceready` イベントの後まで使用できません。 + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + + +## インストール + +これはコルドバ 5.0 + (現在安定 1.0.0) を必要とします。 + + cordova plugin add cordova-plugin-geolocation + + +コルドバの古いバージョンでも非推奨 id (古い 0.3.12 と) 経由でインストールできます。 + + cordova plugin add org.apache.cordova.geolocation + + +また、レポの url 経由で直接インストールすることが可能だ (不安定) + + cordova plugin add https://github.com/apache/cordova-plugin-geolocation.git + + +## サポートされているプラットフォーム + + * アマゾン火 OS + * アンドロイド + * ブラックベリー 10 + * Firefox の OS + * iOS + * Tizen + * Windows Phone 7 と 8 + * Windows 8 + * Windows + +## メソッド + + * navigator.geolocation.getCurrentPosition + * navigator.geolocation.watchPosition + * navigator.geolocation.clearWatch + +## オブジェクト (読み取り専用) + + * Position + * PositionError + * Coordinates + +## navigator.geolocation.getCurrentPosition + +`Position` オブジェクトを `geolocationSuccess` コールバックにパラメーターとしてデバイスの現在位置を返します。 エラーがある場合 `geolocationError` コールバックには、`PositionError` オブジェクトが渡されます。 + + navigator.geolocation.getCurrentPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### パラメーター + + * **geolocationSuccess**: 現在の位置を渡されるコールバック。 + + * **geolocationError**: *(省略可能)*エラーが発生した場合に実行されるコールバック。 + + * **geolocationOptions**: *(オプション)*地理位置情報のオプションです。 + +### 例 + + // 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'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + + +## navigator.geolocation.watchPosition + +位置の変更が検出された場合は、デバイスの現在位置を返します。 取得されると、デバイスの新しい場所、`geolocationSuccess` コールバック パラメーターとして `位置` オブジェクトを実行します。 エラーがある場合、`geolocationError` コールバック パラメーターとして `PositionError` オブジェクトで実行します。 + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### パラメーター + + * **geolocationSuccess**: 現在の位置を渡されるコールバック。 + + * **geolocationError**: (省略可能) エラーが発生した場合に実行されるコールバック。 + + * **geolocationOptions**: (オプション) 地理位置情報のオプションです。 + +### 返します + + * **文字列**: 時計の位置の間隔を参照する時計 id を返します。 時計 id で使用する必要があります `navigator.geolocation.clearWatch` 停止位置の変化を監視します。 + +### 例 + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '
' + + 'Longitude: ' + position.coords.longitude + '
' + + '
' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +地理位置情報 `の位置` の検索をカスタマイズするための省略可能なパラメーター. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### オプション + + * **enableHighAccuracy**: 最高の結果が、アプリケーションに必要があることのヒントを示します。 既定では、デバイスの取得を試みます、 `Position` ネットワーク ベースのメソッドを使用します。 このプロパティを設定する `true` 衛星測位などのより正確な方法を使用するためにフレームワークに指示します。 *(ブール値)* + + * **タイムアウト**: への呼び出しから通過が許可される時間 (ミリ秒単位) の最大長 `navigator.geolocation.getCurrentPosition` または `geolocation.watchPosition` まで対応する、 `geolocationSuccess` コールバックを実行します。 場合は、 `geolocationSuccess` この時間内に、コールバックは呼び出されません、 `geolocationError` コールバックに渡される、 `PositionError.TIMEOUT` のエラー コード。 (と組み合わせて使用するときに注意してください `geolocation.watchPosition` の `geolocationError` 間隔でコールバックを呼び出すことができますすべて `timeout` ミリ秒 !)*(数)* + + * **maximumAge**: 年齢があるミリ秒単位で指定した時間よりも大きくないキャッシュされた位置を受け入れます。*(数)* + +### Android の癖 + +`enableHighAccuracy` オプションが `true` に設定しない限り、アンドロイド 2.x エミュレーター地理位置情報の結果を返さない. + +## navigator.geolocation.clearWatch + +`watchID` パラメーターによって参照される、デバイスの場所への変更を見て停止します。 + + navigator.geolocation.clearWatch(watchID); + + +### パラメーター + + * **watchID**: の id、 `watchPosition` をクリアする間隔。(文字列) + +### 例 + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +`Position` 座標と地理位置情報 API で作成されたタイムスタンプが含まれます。 + +### プロパティ + + * **coords**: 地理的座標のセット。*(座標)* + + * **timestamp**: 作成のタイムスタンプを `coords` 。*(DOMTimeStamp)* + +## Coordinates + +`Coordinates` のオブジェクトは現在の位置のための要求でコールバック関数に使用する `Position` オブジェクトにアタッチされます。 位置の地理座標を記述するプロパティのセットが含まれています。 + +### プロパティ + + * **latitude**: 10 度緯度。*(数)* + + * **longitude**: 10 進度の経度。*(数)* + + * **altitude**: 楕円体上のメートルの位置の高さ。*(数)* + + * **accuracy**: メートルの緯度と経度座標の精度レベル。*(数)* + + * **altitudeAccuracy**: メートルの高度座標の精度レベル。*(数)* + + * **headingし**: 進行方向、カウント、真北から時計回りの角度で指定します。*(数)* + + * **speed**: 毎秒メートルで指定されたデバイスの現在の対地速度。*(数)* + +### アマゾン火 OS 癖 + +**altitudeAccuracy**: `null` を返すことの Android デバイスでサポートされていません. + +### Android の癖 + +**altitudeAccuracy**: `null` を返すことの Android デバイスでサポートされていません. + +## PositionError + +`PositionError` オブジェクト navigator.geolocation でエラーが発生したときに `geolocationError` コールバック関数に渡されます。 + +### プロパティ + + * **コード**: 次のいずれかの定義済みのエラー コード。 + + * **message**: 発生したエラーの詳細を説明するエラー メッセージ。 + +### 定数 + + * `PositionError.PERMISSION_DENIED` + * ユーザーの位置情報を取得するアプリを許可しない場合に返されます。これはプラットフォームに依存します。 + * `PositionError.POSITION_UNAVAILABLE` + * デバイスが、位置を取得することができます返されます。一般に、つまり、デバイスがネットワークに接続されていないまたは衛星の修正を得ることができません。 + * `PositionError.TIMEOUT` + * デバイスがで指定された時間内の位置を取得することができるときに返される、 `timeout` に含まれている `geolocationOptions` 。 使用すると `navigator.geolocation.watchPosition` 、このエラーが繰り返しに渡すことが、 `geolocationError` コールバックごと `timeout` (ミリ秒単位)。 \ No newline at end of file diff --git a/plugins/cordova-plugin-geolocation/doc/ja/index.md b/plugins/cordova-plugin-geolocation/doc/ja/index.md new file mode 100644 index 0000000..3a8b73a --- /dev/null +++ b/plugins/cordova-plugin-geolocation/doc/ja/index.md @@ -0,0 +1,255 @@ + + +# cordova-plugin-geolocation + +このプラグインは緯度や経度などのデバイスの場所に関する情報を提供します。 位置情報の共通のソースはグローバル ポジショニング システム (GPS) と IP アドレス、RFID、WiFi および Bluetooth の MAC アドレス、および GSM/cdma 方式携帯 Id などのネットワーク信号から推定される場所にもあります。 API は、デバイスの実際の場所を返すことの保証はありません。 + +この API は[W3C 地理位置情報 API 仕様][1]に基づいており、既に実装を提供しないデバイス上のみで実行します。 + + [1]: http://dev.w3.org/geo/api/spec-source.html + +**警告**: 地理位置情報データの収集と利用を重要なプライバシーの問題を発生させます。 アプリのプライバシー ポリシーは他の当事者とデータ (たとえば、粗い、罰金、郵便番号レベル、等) の精度のレベルでは共有されているかどうか、アプリが地理位置情報データを使用する方法を議論すべきです。 地理位置情報データと一般に見なされる敏感なユーザーの居場所を開示することができますので、彼らの旅行の歴史保存されている場合。 したがって、アプリのプライバシー ポリシーに加えて、強くする必要があります (デバイス オペレーティング システムしない場合そう既に)、アプリケーションに地理位置情報データをアクセスする前に - 時間のお知らせを提供します。 その通知は、上記の (例えば、 **[ok]**を**おかげで**選択肢を提示する) によってユーザーのアクセス許可を取得するだけでなく、同じ情報を提供する必要があります。 詳細については、プライバシーに関するガイドを参照してください。 + +このプラグインは、グローバル `navigator.geolocation` オブジェクト (プラットフォーム行方不明ですそれ以外の場合) を定義します。 + +オブジェクトは、グローバル スコープでですが、このプラグインによって提供される機能は、`deviceready` イベントの後まで使用できません。 + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + + +## インストール + + cordova plugin add cordova-plugin-geolocation + + +## サポートされているプラットフォーム + +* アマゾン火 OS +* アンドロイド +* ブラックベリー 10 +* Firefox の OS +* iOS +* Tizen +* Windows Phone 7 と 8 +* Windows 8 + +## メソッド + +* navigator.geolocation.getCurrentPosition +* navigator.geolocation.watchPosition +* navigator.geolocation.clearWatch + +## オブジェクト (読み取り専用) + +* Position +* PositionError +* Coordinates + +## navigator.geolocation.getCurrentPosition + +`Position` オブジェクトを `geolocationSuccess` コールバックにパラメーターとしてデバイスの現在位置を返します。 エラーがある場合 `geolocationError` コールバックには、`PositionError` オブジェクトが渡されます。 + + navigator.geolocation.getCurrentPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### パラメーター + +* **geolocationSuccess**: 現在の位置を渡されるコールバック。 + +* **geolocationError**: *(省略可能)*エラーが発生した場合に実行されるコールバック。 + +* **geolocationOptions**: *(オプション)*地理位置情報のオプションです。 + +### 例 + + // 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'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + + +## navigator.geolocation.watchPosition + +位置の変更が検出された場合は、デバイスの現在位置を返します。 取得されると、デバイスの新しい場所、`geolocationSuccess` コールバック パラメーターとして `位置` オブジェクトを実行します。 エラーがある場合、`geolocationError` コールバック パラメーターとして `PositionError` オブジェクトで実行します。 + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### パラメーター + +* **geolocationSuccess**: 現在の位置を渡されるコールバック。 + +* **geolocationError**: (省略可能) エラーが発生した場合に実行されるコールバック。 + +* **geolocationOptions**: (オプション) 地理位置情報のオプションです。 + +### 返します + +* **文字列**: 時計の位置の間隔を参照する時計 id を返します。 時計 id で使用する必要があります `navigator.geolocation.clearWatch` 停止位置の変化を監視します。 + +### 例 + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '
' + + 'Longitude: ' + position.coords.longitude + '
' + + '
' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +地理位置情報 `の位置` の検索をカスタマイズするための省略可能なパラメーター. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### オプション + +* **enableHighAccuracy**: 最高の結果が、アプリケーションに必要があることのヒントを示します。 既定では、デバイスの取得を試みます、 `Position` ネットワーク ベースのメソッドを使用します。 このプロパティを設定する `true` 衛星測位などのより正確な方法を使用するためにフレームワークに指示します。 *(ブール値)* + +* **タイムアウト**: への呼び出しから通過が許可される時間 (ミリ秒単位) の最大長 `navigator.geolocation.getCurrentPosition` または `geolocation.watchPosition` まで対応する、 `geolocationSuccess` コールバックを実行します。 場合は、 `geolocationSuccess` この時間内に、コールバックは呼び出されません、 `geolocationError` コールバックに渡される、 `PositionError.TIMEOUT` のエラー コード。 (と組み合わせて使用するときに注意してください `geolocation.watchPosition` の `geolocationError` 間隔でコールバックを呼び出すことができますすべて `timeout` ミリ秒 !)*(数)* + +* **maximumAge**: 年齢があるミリ秒単位で指定した時間よりも大きくないキャッシュされた位置を受け入れます。*(数)* + +### Android の癖 + +`enableHighAccuracy` オプションが `true` に設定しない限り、アンドロイド 2.x エミュレーター地理位置情報の結果を返さない. + +## navigator.geolocation.clearWatch + +`watchID` パラメーターによって参照される、デバイスの場所への変更を見て停止します。 + + navigator.geolocation.clearWatch(watchID); + + +### パラメーター + +* **watchID**: の id、 `watchPosition` をクリアする間隔。(文字列) + +### 例 + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +`Position` 座標と地理位置情報 API で作成されたタイムスタンプが含まれます。 + +### プロパティ + +* **coords**: 地理的座標のセット。*(座標)* + +* **timestamp**: 作成のタイムスタンプを `coords` 。*(日)* + +## Coordinates + +`Coordinates` のオブジェクトは現在の位置のための要求でコールバック関数に使用する `Position` オブジェクトにアタッチされます。 位置の地理座標を記述するプロパティのセットが含まれています。 + +### プロパティ + +* **latitude**: 10 度緯度。*(数)* + +* **longitude**: 10 進度の経度。*(数)* + +* **altitude**: 楕円体上のメートルの位置の高さ。*(数)* + +* **accuracy**: メートルの緯度と経度座標の精度レベル。*(数)* + +* **altitudeAccuracy**: メートルの高度座標の精度レベル。*(数)* + +* **headingし**: 進行方向、カウント、真北から時計回りの角度で指定します。*(数)* + +* **speed**: 毎秒メートルで指定されたデバイスの現在の対地速度。*(数)* + +### アマゾン火 OS 癖 + +**altitudeAccuracy**: `null` を返すことの Android デバイスでサポートされていません. + +### Android の癖 + +**altitudeAccuracy**: `null` を返すことの Android デバイスでサポートされていません. + +## PositionError + +`PositionError` オブジェクト navigator.geolocation でエラーが発生したときに `geolocationError` コールバック関数に渡されます。 + +### プロパティ + +* **code**: 次のいずれかの定義済みのエラー コード。 + +* **message**: 発生したエラーの詳細を説明するエラー メッセージ。 + +### 定数 + +* `PositionError.PERMISSION_DENIED` + * ユーザーの位置情報を取得するアプリを許可しない場合に返されます。これはプラットフォームに依存します。 +* `PositionError.POSITION_UNAVAILABLE` + * デバイスが、位置を取得することができます返されます。一般に、つまり、デバイスがネットワークに接続されていないまたは衛星の修正を得ることができません。 +* `PositionError.TIMEOUT` + * デバイスがで指定された時間内の位置を取得することができるときに返される、 `timeout` に含まれている `geolocationOptions` 。 使用すると `navigator.geolocation.watchPosition` 、このエラーが繰り返しに渡すことが、 `geolocationError` コールバックごと `timeout` (ミリ秒単位)。 diff --git a/plugins/cordova-plugin-geolocation/doc/ko/README.md b/plugins/cordova-plugin-geolocation/doc/ko/README.md new file mode 100644 index 0000000..dab5005 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/doc/ko/README.md @@ -0,0 +1,268 @@ + + +# cordova-plugin-geolocation + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-geolocation.svg)](https://travis-ci.org/apache/cordova-plugin-geolocation) + +이 플러그인 위도 및 경도 등의 소자의 위치에 대 한 정보를 제공합니다. 일반적인 위치 정보 등 글로벌 포지셔닝 시스템 (GPS) 및 위치와 같은 IP 주소, RFID, WiFi 및 블루투스 MAC 주소 및 GSM/CDMA 셀 Id 네트워크 신호에서 유추 합니다. 보장은 없다는 API 소자의 실제 위치를 반환 합니다. + +이 API [W3C Geolocation API 사양](http://dev.w3.org/geo/api/spec-source.html)에 기반 하 고 이미 구현을 제공 하지 않는 장치에만 실행 됩니다. + +**경고**: 중요 한 개인 정보 보호 문제를 제기 하는 위치 정보 데이터의 수집 및 사용 합니다. 응용 프로그램의 개인 정보 보호 정책 다른 당사자와의 데이터 (예를 들어, 굵고, 괜 찮 아 요, 우편 번호, 등)의 정밀도 수준을 공유 여부를 app 지리적 데이터를 사용 하는 방법 토론 해야 한다. 그것은 사용자의 행방을 밝힐 수 있기 때문에 및 저장, 그들의 여행 역사 지리적 위치 데이터는 일반적으로 민감한 간주. 따라서, 애플 리 케이 션의 개인 정보 보호 정책 뿐만 아니라 강력 하 게 좋습니다 (해당 되는 경우 장치 운영 체제 이렇게 이미 하지 않는) 응용 프로그램 위치 정보 데이터에 액세스 하기 전에 그냥--시간 통지. 그 통지는 (예를 들어, **확인** 및 **아니오**선택 제시) 하 여 사용자의 허가 취득 뿐만 아니라, 위에서 언급 된 동일한 정보를 제공 해야 합니다. 자세한 내용은 개인 정보 보호 가이드를 참조 하십시오. + +이 플러그인 (플랫폼은 그렇지 않으면 누락 된)에 대 한 전역 `navigator.geolocation` 개체를 정의 합니다. + +개체가 전역 범위에 있지만,이 플러그인에 의해 제공 되는 기능 하지 사용할 수 있습니다까지 `deviceready` 이벤트 후. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + + +## 설치 + +코르도바 5.0 + (현재 안정적인 1.0.0) 필요 + + cordova plugin add cordova-plugin-geolocation + + +코르도바의 이전 버전 사용 되지 않는 id (부실 0.3.12)를 통해 설치할 수 있습니다. + + cordova plugin add org.apache.cordova.geolocation + + +그것은 또한 배상 계약 url을 통해 직접 설치할 수 (불안정) + + cordova plugin add https://github.com/apache/cordova-plugin-geolocation.git + + +## 지원 되는 플랫폼 + + * 아마존 화재 운영 체제 + * 안 드 로이드 + * 블랙베리 10 + * Firefox 운영 체제 + * iOS + * Tizen + * Windows Phone 7과 8 + * 윈도우 8 + * 윈도우 + +## 메서드 + + * navigator.geolocation.getCurrentPosition + * navigator.geolocation.watchPosition + * navigator.geolocation.clearWatch + +## (읽기 전용) 개체 + + * Position + * PositionError + * Coordinates + +## navigator.geolocation.getCurrentPosition + +매개 변수 `Position` 개체와 `geolocationSuccess`를 디바이스의 현재 위치를 반환합니다. 오류가 있는 경우에, `geolocationError` 콜백 `PositionError` 개체에 전달 됩니다. + + navigator.geolocation.getCurrentPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### 매개 변수 + + * **geolocationSuccess**: 현재의 위치를 전달 되는 콜백. + + * **geolocationError**: *(선택 사항)* 오류가 발생 하면 실행 되는 콜백. + + * **geolocationOptions**: *(선택 사항)* 위치 옵션. + +### 예를 들어 + + // 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'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + + +## navigator.geolocation.watchPosition + +위치에 변화를 탐지할 때 소자의 현재 위치를 반환 합니다. 장치 새 위치를 검색 하는 경우 `geolocationSuccess` 콜백 매개 변수로 개체를 `Position`으로 실행 합니다. 오류가 있는 경우에, `geolocationError` 콜백 매개 변수로 `PositionError` 개체를 실행 합니다. + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### 매개 변수 + + * **geolocationSuccess**: 현재의 위치를 전달 되는 콜백. + + * **geolocationError**: (선택 사항) 오류가 발생 하면 실행 되는 콜백. + + * **geolocationOptions**: (선택 사항)는 지리적 위치 옵션. + +### 반환 + + * **문자열**: 시계 위치 간격을 참조 하는 시계 id를 반환 합니다. 시계 id와 함께 사용 해야 합니다 `navigator.geolocation.clearWatch` 위치 변화에 대 한 보고 중지. + +### 예를 들어 + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '
' + + 'Longitude: ' + position.coords.longitude + '
' + + '
' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +지리적 `Position` 검색을 사용자 지정 하는 선택적 매개 변수. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### 옵션 + + * **enableHighAccuracy**: 힌트는 응용 프로그램에 필요한 최상의 결과 제공 합니다. 기본적으로 장치를 검색 하려고 한 `Position` 네트워크 기반 방법을 사용 하 여. 이 속성을 설정 `true` 위성 위치 등 보다 정확한 방법을 사용 하 여 프레임 워크. *(부울)* + + * **시간 제한**: 최대 시간의 길이 (밀리초) 호출에서 전달할 수 있는 `navigator.geolocation.getCurrentPosition` 또는 `geolocation.watchPosition` 해당까지 `geolocationSuccess` 콜백 실행. 경우는 `geolocationSuccess` 콜백이이 시간 내에서 호출 되지 않습니다는 `geolocationError` 콜백 전달 되는 `PositionError.TIMEOUT` 오류 코드. (함께 사용 하는 경우 `geolocation.watchPosition` , `geolocationError` 콜백 간격에서 호출 될 수 있는 모든 `timeout` 밀리초!) *(수)* + + * **maximumAge**: 밀리초 단위로 지정 된 시간 보다 더 큰 되는 캐시 위치를 수락 합니다. *(수)* + +### 안 드 로이드 단점 + +`EnableHighAccuracy` 옵션을 `true`로 설정 되어 있지 않으면 안 드 로이드 2.x 에뮬레이터 위치 결과 반환 하지 않는. + +## navigator.geolocation.clearWatch + +`watchID` 매개 변수에서 참조 하는 소자의 위치 변경에 대 한 보고 중지 합니다. + + navigator.geolocation.clearWatch(watchID); + + +### 매개 변수 + + * **watchID**: id는 `watchPosition` 간격을 취소 합니다. (문자열) + +### 예를 들어 + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +`Position` 좌표 및 지리적 위치 API에 의해 생성 하는 타임 스탬프를 포함 합니다. + +### 속성 + + * **coords**: 지리적 좌표 집합. *(좌표)* + + * **timestamp**: 생성 타임 스탬프에 대 한 `coords` . *(DOMTimeStamp)* + +## Coordinates + +`Coordinates` 개체를 현재 위치에 대 한 요청에 콜백 함수를 사용할 수 있는 `Position` 개체에 첨부 됩니다. 그것은 위치의 지리적 좌표를 설명 하는 속성 집합이 포함 되어 있습니다. + +### 속성 + + * **latitude**: 소수점도 위도. *(수)* + + * **longitude**: 경도 10 진수 각도. *(수)* + + * **altitude**: 높이의 타원 면 미터에 위치. *(수)* + + * **정확도**: 정확도 레벨 미터에 위도 및 경도 좌표. *(수)* + + * **altitudeAccuracy**: 미터에 고도 좌표의 정확도 수준. *(수)* + + * **heading**: 여행, 진 북을 기준으로 시계 방향으로 세도에 지정 된 방향으로. *(수)* + + * **speed**: 초당 미터에 지정 된 디바이스의 현재 땅 속도. *(수)* + +### 아마존 화재 OS 단점 + +**altitudeAccuracy**: `null` 반환 안 드 로이드 장치에 의해 지원 되지 않습니다. + +### 안 드 로이드 단점 + +**altitudeAccuracy**: `null` 반환 안 드 로이드 장치에 의해 지원 되지 않습니다. + +## PositionError + +`PositionError` 개체는 navigator.geolocation와 함께 오류가 발생 하면 `geolocationError` 콜백 함수에 전달 됩니다. + +### 속성 + + * **코드**: 미리 정의 된 오류 코드 중 하나가 아래에 나열 된. + + * **message**: 발생 한 오류 세부 정보를 설명 하는 오류 메시지. + +### 상수 + + * `PositionError.PERMISSION_DENIED` + * 사용자가 위치 정보를 검색 애플 리 케이 션을 허용 하지 않는 경우 반환 됩니다. 이 플랫폼에 따라 달라 집니다. + * `PositionError.POSITION_UNAVAILABLE` + * 장치 위치를 검색할 수 없을 때 반환 합니다. 일반적으로,이 장치는 네트워크에 연결 되어 있지 않은 또는 위성 수정 프로그램을 얻을 수 없습니다 의미 합니다. + * `PositionError.TIMEOUT` + * 장치에 지정 된 시간 내에서 위치를 검색할 수 없는 경우 반환 되는 `timeout` 에 포함 된 `geolocationOptions` . 함께 사용 될 때 `navigator.geolocation.watchPosition` ,이 오류를 반복적으로 전달 될 수는 `geolocationError` 콜백 매 `timeout` 밀리초. \ No newline at end of file diff --git a/plugins/cordova-plugin-geolocation/doc/ko/index.md b/plugins/cordova-plugin-geolocation/doc/ko/index.md new file mode 100644 index 0000000..19f47c7 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/doc/ko/index.md @@ -0,0 +1,255 @@ + + +# cordova-plugin-geolocation + +이 플러그인 위도 및 경도 등의 소자의 위치에 대 한 정보를 제공합니다. 일반적인 위치 정보 등 글로벌 포지셔닝 시스템 (GPS) 및 위치와 같은 IP 주소, RFID, WiFi 및 블루투스 MAC 주소 및 GSM/CDMA 셀 Id 네트워크 신호에서 유추 합니다. 보장은 없다는 API 소자의 실제 위치를 반환 합니다. + +이 API [W3C Geolocation API 사양][1]에 기반 하 고 이미 구현을 제공 하지 않는 장치에만 실행 됩니다. + + [1]: http://dev.w3.org/geo/api/spec-source.html + +**경고**: 중요 한 개인 정보 보호 문제를 제기 하는 위치 정보 데이터의 수집 및 사용 합니다. 응용 프로그램의 개인 정보 보호 정책 다른 당사자와의 데이터 (예를 들어, 굵고, 괜 찮 아 요, 우편 번호, 등)의 정밀도 수준을 공유 여부를 app 지리적 데이터를 사용 하는 방법 토론 해야 한다. 그것은 사용자의 행방을 밝힐 수 있기 때문에 및 저장, 그들의 여행 역사 지리적 위치 데이터는 일반적으로 민감한 간주. 따라서, 애플 리 케이 션의 개인 정보 보호 정책 뿐만 아니라 강력 하 게 좋습니다 (해당 되는 경우 장치 운영 체제 이렇게 이미 하지 않는) 응용 프로그램 위치 정보 데이터에 액세스 하기 전에 그냥--시간 통지. 그 통지는 (예를 들어, **확인** 및 **아니오**선택 제시) 하 여 사용자의 허가 취득 뿐만 아니라, 위에서 언급 된 동일한 정보를 제공 해야 합니다. 자세한 내용은 개인 정보 보호 가이드를 참조 하십시오. + +이 플러그인 (플랫폼은 그렇지 않으면 누락 된)에 대 한 전역 `navigator.geolocation` 개체를 정의 합니다. + +개체가 전역 범위에 있지만,이 플러그인에 의해 제공 되는 기능 하지 사용할 수 있습니다까지 `deviceready` 이벤트 후. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + + +## 설치 + + cordova plugin add cordova-plugin-geolocation + + +## 지원 되는 플랫폼 + +* 아마존 화재 운영 체제 +* 안 드 로이드 +* 블랙베리 10 +* Firefox 운영 체제 +* iOS +* Tizen +* Windows Phone 7과 8 +* 윈도우 8 + +## 메서드 + +* navigator.geolocation.getCurrentPosition +* navigator.geolocation.watchPosition +* navigator.geolocation.clearWatch + +## (읽기 전용) 개체 + +* Position +* PositionError +* Coordinates + +## navigator.geolocation.getCurrentPosition + +매개 변수 `Position` 개체와 `geolocationSuccess`를 디바이스의 현재 위치를 반환합니다. 오류가 있는 경우에, `geolocationError` 콜백 `PositionError` 개체에 전달 됩니다. + + navigator.geolocation.getCurrentPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### 매개 변수 + +* **geolocationSuccess**: 현재의 위치를 전달 되는 콜백. + +* **geolocationError**: *(선택 사항)* 오류가 발생 하면 실행 되는 콜백. + +* **geolocationOptions**: *(선택 사항)* 위치 옵션. + +### 예를 들어 + + // 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'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + + +## navigator.geolocation.watchPosition + +위치에 변화를 탐지할 때 소자의 현재 위치를 반환 합니다. 장치 새 위치를 검색 하는 경우 `geolocationSuccess` 콜백 매개 변수로 개체를 `Position`으로 실행 합니다. 오류가 있는 경우에, `geolocationError` 콜백 매개 변수로 `PositionError` 개체를 실행 합니다. + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### 매개 변수 + +* **geolocationSuccess**: 현재의 위치를 전달 되는 콜백. + +* **geolocationError**: (선택 사항) 오류가 발생 하면 실행 되는 콜백. + +* **geolocationOptions**: (선택 사항)는 지리적 위치 옵션. + +### 반환 + +* **문자열**: 시계 위치 간격을 참조 하는 시계 id를 반환 합니다. 시계 id와 함께 사용 해야 합니다 `navigator.geolocation.clearWatch` 위치 변화에 대 한 보고 중지. + +### 예를 들어 + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '
' + + 'Longitude: ' + position.coords.longitude + '
' + + '
' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +지리적 `Position` 검색을 사용자 지정 하는 선택적 매개 변수. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### 옵션 + +* **enableHighAccuracy**: 힌트는 응용 프로그램에 필요한 최상의 결과 제공 합니다. 기본적으로 장치를 검색 하려고 한 `Position` 네트워크 기반 방법을 사용 하 여. 이 속성을 설정 `true` 위성 위치 등 보다 정확한 방법을 사용 하 여 프레임 워크. *(부울)* + +* **시간 제한**: 최대 시간의 길이 (밀리초) 호출에서 전달할 수 있는 `navigator.geolocation.getCurrentPosition` 또는 `geolocation.watchPosition` 해당까지 `geolocationSuccess` 콜백 실행. 경우는 `geolocationSuccess` 콜백이이 시간 내에서 호출 되지 않습니다는 `geolocationError` 콜백 전달 되는 `PositionError.TIMEOUT` 오류 코드. (함께 사용 하는 경우 `geolocation.watchPosition` , `geolocationError` 콜백 간격에서 호출 될 수 있는 모든 `timeout` 밀리초!) *(수)* + +* **maximumAge**: 밀리초 단위로 지정 된 시간 보다 더 큰 되는 캐시 위치를 수락 합니다. *(수)* + +### 안 드 로이드 단점 + +`EnableHighAccuracy` 옵션을 `true`로 설정 되어 있지 않으면 안 드 로이드 2.x 에뮬레이터 위치 결과 반환 하지 않는. + +## navigator.geolocation.clearWatch + +`watchID` 매개 변수에서 참조 하는 소자의 위치 변경에 대 한 보고 중지 합니다. + + navigator.geolocation.clearWatch(watchID); + + +### 매개 변수 + +* **watchID**: id는 `watchPosition` 간격을 취소 합니다. (문자열) + +### 예를 들어 + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +`Position` 좌표 및 지리적 위치 API에 의해 생성 하는 타임 스탬프를 포함 합니다. + +### 속성 + +* **coords**: 지리적 좌표 집합. *(좌표)* + +* **timestamp**: 생성 타임 스탬프에 대 한 `coords` . *(DOMTimeStamp)* + +## Coordinates + +`Coordinates` 개체를 현재 위치에 대 한 요청에 콜백 함수를 사용할 수 있는 `Position` 개체에 첨부 됩니다. 그것은 위치의 지리적 좌표를 설명 하는 속성 집합이 포함 되어 있습니다. + +### 속성 + +* **latitude**: 소수점도 위도. *(수)* + +* **longitude**: 경도 10 진수 각도. *(수)* + +* **altitude**: 높이의 타원 면 미터에 위치. *(수)* + +* **정확도**: 정확도 레벨 미터에 위도 및 경도 좌표. *(수)* + +* **altitudeAccuracy**: 미터에 고도 좌표의 정확도 수준. *(수)* + +* **heading**: 여행, 진 북을 기준으로 시계 방향으로 세도에 지정 된 방향으로. *(수)* + +* **speed**: 초당 미터에 지정 된 디바이스의 현재 땅 속도. *(수)* + +### 아마존 화재 OS 단점 + +**altitudeAccuracy**: `null` 반환 안 드 로이드 장치에 의해 지원 되지 않습니다. + +### 안 드 로이드 단점 + +**altitudeAccuracy**: `null` 반환 안 드 로이드 장치에 의해 지원 되지 않습니다. + +## PositionError + +`PositionError` 개체는 navigator.geolocation와 함께 오류가 발생 하면 `geolocationError` 콜백 함수에 전달 됩니다. + +### 속성 + +* **code**: 미리 정의 된 오류 코드 중 하나가 아래에 나열 된. + +* **message**: 발생 한 오류 세부 정보를 설명 하는 오류 메시지. + +### 상수 + +* `PositionError.PERMISSION_DENIED` + * 사용자가 위치 정보를 검색 애플 리 케이 션을 허용 하지 않는 경우 반환 됩니다. 이 플랫폼에 따라 달라 집니다. +* `PositionError.POSITION_UNAVAILABLE` + * 장치 위치를 검색할 수 없을 때 반환 합니다. 일반적으로,이 장치는 네트워크에 연결 되어 있지 않은 또는 위성 수정 프로그램을 얻을 수 없습니다 의미 합니다. +* `PositionError.TIMEOUT` + * 장치에 지정 된 시간 내에서 위치를 검색할 수 없는 경우 반환 되는 `timeout` 에 포함 된 `geolocationOptions` . 함께 사용 될 때 `navigator.geolocation.watchPosition` ,이 오류를 반복적으로 전달 될 수는 `geolocationError` 콜백 매 `timeout` 밀리초. diff --git a/plugins/cordova-plugin-geolocation/doc/pl/README.md b/plugins/cordova-plugin-geolocation/doc/pl/README.md new file mode 100644 index 0000000..0ef35c4 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/doc/pl/README.md @@ -0,0 +1,268 @@ + + +# cordova-plugin-geolocation + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-geolocation.svg)](https://travis-ci.org/apache/cordova-plugin-geolocation) + +Ten plugin zawiera informacje o lokalizacji urządzenia, takie jak szerokość i długość geograficzną. Najczęstsze źródła informacji o lokalizacji obejmują Global Positioning System (GPS) i lokalizacji wywnioskować z sieci sygnały, takie jak adres IP, RFID, WiFi i Bluetooth MAC adresy, a komórki GSM/CDMA identyfikatorów. Nie ma żadnej gwarancji, że API zwraca rzeczywistej lokalizacji urządzenia. + +Ten interfejs API jest oparty na [Specyfikacji W3C Geolocation API](http://dev.w3.org/geo/api/spec-source.html)i tylko wykonuje na urządzeniach, które już nie zapewniają implementacja. + +**Ostrzeżenie**: zbierania i wykorzystywania danych geolokacyjnych podnosi kwestie prywatności ważne. Polityka prywatności danej aplikacji należy omówić, jak aplikacja używa danych, czy jest on dzielony z innych stron i poziom dokładności danych (na przykład, gruba, porządku, kod pocztowy poziom, itp.). Danych geolokacyjnych ogólnie uznaje wrażliwych, bo to może ujawnić pobytu użytkownika i, jeśli przechowywane, historii ich podróży. W związku z tym oprócz aplikacji prywatności, zdecydowanie warto powiadomienia just-in-time, zanim aplikacja uzyskuje dostęp do danych (jeśli urządzenie system operacyjny nie robi już). Że ogłoszenie powinno zawierać te same informacje, o których wspomniano powyżej, jak również uzyskanie uprawnienia użytkownika (np. poprzez przedstawianie wyborów **OK** i **Nie dzięki**). Aby uzyskać więcej informacji zobacz przewodnik prywatności. + +Ten plugin definiuje obiekt globalny `navigator.geolocation` (dla platformy gdzie to inaczej brak). + +Mimo, że obiekt jest w globalnym zasięgu, funkcji oferowanych przez ten plugin nie są dostępne dopiero po turnieju `deviceready`. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + + +## Instalacja + +Wymaga to cordova 5.0 + (bieżącej stabilnej 1.0.0) + + cordova plugin add cordova-plugin-geolocation + + +Starsze wersje cordova nadal można zainstalować za pomocą niezalecany identyfikator (starych 0.3.12) + + cordova plugin add org.apache.cordova.geolocation + + +Jest również możliwość instalacji za pośrednictwem repo url bezpośrednio (niestabilny) + + cordova plugin add https://github.com/apache/cordova-plugin-geolocation.git + + +## Obsługiwane platformy + + * Amazon Fire OS + * Android + * BlackBerry 10 + * Firefox OS + * iOS + * Tizen + * Windows Phone 7 i 8 + * Windows 8 + * Windows + +## Metody + + * navigator.geolocation.getCurrentPosition + * navigator.geolocation.watchPosition + * navigator.geolocation.clearWatch + +## Obiekty (tylko do odczytu) + + * Position + * PositionError + * Coordinates + +## navigator.geolocation.getCurrentPosition + +Zwraca bieżącą pozycję urządzenia do `geolocationSuccess` wywołanie zwrotne z `Position` obiektu jako parametr. Jeśli występuje błąd, wywołania zwrotnego `geolocationError` jest przekazywany obiekt `PositionError`. + + navigator.geolocation.getCurrentPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### Parametry + + * **geolocationSuccess**: wywołania zwrotnego, który jest przekazywany aktualnej pozycji. + + * **geolocationError**: *(opcjonalne)* wywołania zwrotnego, która wykonuje w przypadku wystąpienia błędu. + + * **geolocationOptions**: *(opcjonalne)* opcji geolokalizacji. + +### Przykład + + // 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'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + + +## navigator.geolocation.watchPosition + +Zwraca bieżącą pozycję urządzenia po wykryciu zmiany pozycji. Gdy urządzenie pobiera nową lokalizację, wywołania zwrotnego `geolocationSuccess` wykonuje się z `Position` obiektu jako parametr. Jeśli występuje błąd, wywołania zwrotnego `geolocationError` wykonuje się z obiektem `PositionError` jako parametr. + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### Parametry + + * **geolocationSuccess**: wywołania zwrotnego, który jest przekazywany aktualnej pozycji. + + * **geolocationError**: (opcjonalne) wywołania zwrotnego, która wykonuje w przypadku wystąpienia błędu. + + * **geolocationOptions**: (opcjonalne) geolocation opcje. + +### Zwraca + + * **Napis**: zwraca identyfikator zegarek, który odwołuje się oglądać pozycji interwał. Identyfikator zegarek powinny być używane z `navigator.geolocation.clearWatch` Aby przestać oglądać do zmiany pozycji. + +### Przykład + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '
' + + 'Longitude: ' + position.coords.longitude + '
' + + '
' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +Parametry opcjonalne dostosować pobierania geolocation `Position`. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### Opcje + + * **enableHighAccuracy**: stanowi wskazówkę, że aplikacja musi możliwie najlepszych rezultatów. Domyślnie, urządzenie próbuje pobrać `Position` przy użyciu metody oparte na sieci. Ustawienie tej właściwości na `true` mówi ramach dokładniejszych metod, takich jak pozycjonowanie satelitarne. *(Wartość logiczna)* + + * **Limit czasu**: maksymalna długość czas (w milisekundach), który może przekazać wywołanie `navigator.geolocation.getCurrentPosition` lub `geolocation.watchPosition` do odpowiednich `geolocationSuccess` wykonuje wywołanie zwrotne. Jeśli `geolocationSuccess` wywołania zwrotnego nie jest wywoływany w tej chwili, `geolocationError` wywołania zwrotnego jest przekazywany `PositionError.TIMEOUT` kod błędu. (Należy zauważyć, że w połączeniu z `geolocation.watchPosition` , `geolocationError` wywołania zwrotnego można nazwać w odstępie co `timeout` milisekund!) *(Liczba)* + + * **maximumAge**: przyjąć buforowane pozycji, w których wiek jest nie większa niż określony czas w milisekundach. *(Liczba)* + +### Dziwactwa Androida + +Emulatory Androida 2.x nie zwracają wynik geolocation, chyba że opcja `enableHighAccuracy` jest ustawiona na `wartość true`. + +## navigator.geolocation.clearWatch + +Przestać oglądać zmiany położenia urządzenia określany przez parametr `watchID`. + + navigator.geolocation.clearWatch(watchID); + + +### Parametry + + * **watchID**: identyfikator `watchPosition` Interwał jasne. (String) + +### Przykład + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +Zawiera współrzędne `Position` i sygnatury czasowej, stworzony przez geolocation API. + +### Właściwości + + * **coords**: zestaw współrzędnych geograficznych. *(Współrzędne)* + + * **timestamp**: Sygnatura czasowa utworzenia dla `coords` . *(DOMTimeStamp)* + +## Coordinates + +`Coordinates` obiektu jest dołączone do `Position` obiektu, który jest dostępny dla funkcji wywołania zwrotnego w prośby o aktualnej pozycji. Zawiera zestaw właściwości, które opisują geograficzne współrzędne pozycji. + +### Właściwości + + * **szerokość geograficzna**: Latitude w stopniach dziesiętnych. *(Liczba)* + + * **długość geograficzna**: długość geograficzna w stopniach dziesiętnych. *(Liczba)* + + * **wysokość**: wysokość pozycji metrów nad elipsoidalny. *(Liczba)* + + * **dokładność**: poziom dokładności współrzędnych szerokości i długości geograficznej w metrach. *(Liczba)* + + * **altitudeAccuracy**: poziom dokładności Współrzędna wysokość w metrach. *(Liczba)* + + * **pozycja**: kierunek podróży, określonego w stopni licząc ruchu wskazówek zegara względem północy rzeczywistej. *(Liczba)* + + * **prędkość**: Aktualna prędkość ziemi urządzenia, określone w metrach na sekundę. *(Liczba)* + +### Amazon ogień OS dziwactwa + +**altitudeAccuracy**: nie obsługiwane przez Android urządzeń, zwracanie `wartości null`. + +### Dziwactwa Androida + +**altitudeAccuracy**: nie obsługiwane przez Android urządzeń, zwracanie `wartości null`. + +## PositionError + +`PositionError` obiekt jest przekazywany do funkcji wywołania zwrotnego `geolocationError`, gdy wystąpi błąd z navigator.geolocation. + +### Właściwości + + * **Kod**: jeden z kodów błędów wstępnie zdefiniowanych poniżej. + + * **wiadomość**: komunikat o błędzie, opisując szczegóły wystąpił błąd. + +### Stałe + + * `PositionError.PERMISSION_DENIED` + * Zwracane, gdy użytkownicy nie zezwalają aplikacji do pobierania informacji o pozycji. Jest to zależne od platformy. + * `PositionError.POSITION_UNAVAILABLE` + * Zwracane, gdy urządzenie jest w stanie pobrać pozycji. Ogólnie rzecz biorąc oznacza to urządzenie nie jest podłączone do sieci lub nie może uzyskać satelita utrwalić. + * `PositionError.TIMEOUT` + * Zwracane, gdy urządzenie jest w stanie pobrać pozycji w czasie określonym przez `timeout` w `geolocationOptions` . Gdy używana z `navigator.geolocation.watchPosition` , ten błąd może być wielokrotnie przekazywane do `geolocationError` zwrotne co `timeout` milisekund. \ No newline at end of file diff --git a/plugins/cordova-plugin-geolocation/doc/pl/index.md b/plugins/cordova-plugin-geolocation/doc/pl/index.md new file mode 100644 index 0000000..6d08320 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/doc/pl/index.md @@ -0,0 +1,255 @@ + + +# cordova-plugin-geolocation + +Ten plugin zawiera informacje o lokalizacji urządzenia, takie jak szerokość i długość geograficzną. Najczęstsze źródła informacji o lokalizacji obejmują Global Positioning System (GPS) i lokalizacji wywnioskować z sieci sygnały, takie jak adres IP, RFID, WiFi i Bluetooth MAC adresy, a komórki GSM/CDMA identyfikatorów. Nie ma żadnej gwarancji, że API zwraca rzeczywistej lokalizacji urządzenia. + +Ten interfejs API jest oparty na [Specyfikacji W3C Geolocation API][1]i tylko wykonuje na urządzeniach, które już nie zapewniają implementacja. + + [1]: http://dev.w3.org/geo/api/spec-source.html + +**Ostrzeżenie**: zbierania i wykorzystywania danych geolokacyjnych podnosi kwestie prywatności ważne. Polityka prywatności danej aplikacji należy omówić, jak aplikacja używa danych, czy jest on dzielony z innych stron i poziom dokładności danych (na przykład, gruba, porządku, kod pocztowy poziom, itp.). Danych geolokacyjnych ogólnie uznaje wrażliwych, bo to może ujawnić pobytu użytkownika i, jeśli przechowywane, historii ich podróży. W związku z tym oprócz aplikacji prywatności, zdecydowanie warto powiadomienia just-in-time, zanim aplikacja uzyskuje dostęp do danych (jeśli urządzenie system operacyjny nie robi już). Że ogłoszenie powinno zawierać te same informacje, o których wspomniano powyżej, jak również uzyskanie uprawnienia użytkownika (np. poprzez przedstawianie wyborów **OK** i **Nie dzięki**). Aby uzyskać więcej informacji zobacz przewodnik prywatności. + +Ten plugin definiuje obiekt globalny `navigator.geolocation` (dla platformy gdzie to inaczej brak). + +Mimo, że obiekt jest w globalnym zasięgu, funkcji oferowanych przez ten plugin nie są dostępne dopiero po turnieju `deviceready`. + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + + +## Instalacja + + cordova plugin add cordova-plugin-geolocation + + +## Obsługiwane platformy + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 i 8 +* Windows 8 + +## Metody + +* navigator.geolocation.getCurrentPosition +* navigator.geolocation.watchPosition +* navigator.geolocation.clearWatch + +## Obiekty (tylko do odczytu) + +* Stanowisko +* PositionError +* Coordinates + +## navigator.geolocation.getCurrentPosition + +Zwraca bieżącą pozycję urządzenia do `geolocationSuccess` wywołanie zwrotne z `Position` obiektu jako parametr. Jeśli występuje błąd, wywołania zwrotnego `geolocationError` jest przekazywany obiekt `PositionError`. + + navigator.geolocation.getCurrentPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### Parametry + +* **geolocationSuccess**: wywołania zwrotnego, który jest przekazywany aktualnej pozycji. + +* **geolocationError**: *(opcjonalne)* wywołania zwrotnego, która wykonuje w przypadku wystąpienia błędu. + +* **geolocationOptions**: *(opcjonalne)* opcji geolokalizacji. + +### Przykład + + // 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'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + + +## navigator.geolocation.watchPosition + +Zwraca bieżącą pozycję urządzenia po wykryciu zmiany pozycji. Gdy urządzenie pobiera nową lokalizację, wywołania zwrotnego `geolocationSuccess` wykonuje się z `Position` obiektu jako parametr. Jeśli występuje błąd, wywołania zwrotnego `geolocationError` wykonuje się z obiektem `PositionError` jako parametr. + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### Parametry + +* **geolocationSuccess**: wywołania zwrotnego, który jest przekazywany aktualnej pozycji. + +* **geolocationError**: (opcjonalne) wywołania zwrotnego, która wykonuje w przypadku wystąpienia błędu. + +* **geolocationOptions**: (opcjonalne) geolocation opcje. + +### Zwraca + +* **Napis**: zwraca identyfikator zegarek, który odwołuje się oglądać pozycji interwał. Identyfikator zegarek powinny być używane z `navigator.geolocation.clearWatch` Aby przestać oglądać do zmiany pozycji. + +### Przykład + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '
' + + 'Longitude: ' + position.coords.longitude + '
' + + '
' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +Parametry opcjonalne dostosować pobierania geolocation `Position`. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### Opcje + +* **enableHighAccuracy**: stanowi wskazówkę, że aplikacja musi możliwie najlepszych rezultatów. Domyślnie, urządzenie próbuje pobrać `Position` przy użyciu metody oparte na sieci. Ustawienie tej właściwości na `true` mówi ramach dokładniejszych metod, takich jak pozycjonowanie satelitarne. *(Wartość logiczna)* + +* **Limit czasu**: maksymalna długość czas (w milisekundach), który może przekazać wywołanie `navigator.geolocation.getCurrentPosition` lub `geolocation.watchPosition` do odpowiednich `geolocationSuccess` wykonuje wywołanie zwrotne. Jeśli `geolocationSuccess` wywołania zwrotnego nie jest wywoływany w tej chwili, `geolocationError` wywołania zwrotnego jest przekazywany `PositionError.TIMEOUT` kod błędu. (Należy zauważyć, że w połączeniu z `geolocation.watchPosition` , `geolocationError` wywołania zwrotnego można nazwać w odstępie co `timeout` milisekund!) *(Liczba)* + +* **maximumAge**: przyjąć buforowane pozycji, w których wiek jest nie większa niż określony czas w milisekundach. *(Liczba)* + +### Dziwactwa Androida + +Emulatory Androida 2.x nie zwracają wynik geolocation, chyba że opcja `enableHighAccuracy` jest ustawiona na `wartość true`. + +## navigator.geolocation.clearWatch + +Przestać oglądać zmiany położenia urządzenia określany przez parametr `watchID`. + + navigator.geolocation.clearWatch(watchID); + + +### Parametry + +* **watchID**: identyfikator `watchPosition` Interwał jasne. (String) + +### Przykład + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + + +## Stanowisko + +Zawiera współrzędne `Position` i sygnatury czasowej, stworzony przez geolocation API. + +### Właściwości + +* **coords**: zestaw współrzędnych geograficznych. *(Współrzędne)* + +* **sygnatura czasowa**: Sygnatura czasowa utworzenia dla `coords` . *(Data)* + +## Coordinates + +`Coordinates` obiektu jest dołączone do `Position` obiektu, który jest dostępny dla funkcji wywołania zwrotnego w prośby o aktualnej pozycji. Zawiera zestaw właściwości, które opisują geograficzne współrzędne pozycji. + +### Właściwości + +* **szerokość geograficzna**: Latitude w stopniach dziesiętnych. *(Liczba)* + +* **długość geograficzna**: długość geograficzna w stopniach dziesiętnych. *(Liczba)* + +* **wysokość**: wysokość pozycji metrów nad elipsoidalny. *(Liczba)* + +* **dokładność**: poziom dokładności współrzędnych szerokości i długości geograficznej w metrach. *(Liczba)* + +* **altitudeAccuracy**: poziom dokładności Współrzędna wysokość w metrach. *(Liczba)* + +* **pozycja**: kierunek podróży, określonego w stopni licząc ruchu wskazówek zegara względem północy rzeczywistej. *(Liczba)* + +* **prędkość**: Aktualna prędkość ziemi urządzenia, określone w metrach na sekundę. *(Liczba)* + +### Amazon ogień OS dziwactwa + +**altitudeAccuracy**: nie obsługiwane przez Android urządzeń, zwracanie `wartości null`. + +### Dziwactwa Androida + +**altitudeAccuracy**: nie obsługiwane przez Android urządzeń, zwracanie `wartości null`. + +## PositionError + +`PositionError` obiekt jest przekazywany do funkcji wywołania zwrotnego `geolocationError`, gdy wystąpi błąd z navigator.geolocation. + +### Właściwości + +* **Kod**: jeden z kodów błędów wstępnie zdefiniowanych poniżej. + +* **wiadomość**: komunikat o błędzie, opisując szczegóły wystąpił błąd. + +### Stałe + +* `PositionError.PERMISSION_DENIED` + * Zwracane, gdy użytkownicy nie zezwalają aplikacji do pobierania informacji o pozycji. Jest to zależne od platformy. +* `PositionError.POSITION_UNAVAILABLE` + * Zwracane, gdy urządzenie jest w stanie pobrać pozycji. Ogólnie rzecz biorąc oznacza to urządzenie nie jest podłączone do sieci lub nie może uzyskać satelita utrwalić. +* `PositionError.TIMEOUT` + * Zwracane, gdy urządzenie jest w stanie pobrać pozycji w czasie określonym przez `timeout` w `geolocationOptions` . Gdy używana z `navigator.geolocation.watchPosition` , ten błąd może być wielokrotnie przekazywane do `geolocationError` zwrotne co `timeout` milisekund. diff --git a/plugins/cordova-plugin-geolocation/doc/ru/index.md b/plugins/cordova-plugin-geolocation/doc/ru/index.md new file mode 100644 index 0000000..3d9c766 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/doc/ru/index.md @@ -0,0 +1,206 @@ + + +# cordova-plugin-geolocation + +Этот плагин предоставляет информацию о местоположении устройства, например, Широта и Долгота. Общие источники информации о местонахождении включают глобальной системы позиционирования (GPS) и местоположение, выведено из сети сигналов, таких как IP-адрес, RFID, WiFi и Bluetooth MAC-адреса и идентификаторы базовых станций сотовой GSM/CDMA. Нет никакой гарантии, что API возвращает фактическое местоположение устройства. + +Этот API основан на [Спецификации W3C Geolocation API][1]и выполняется только на устройствах, которые уже не обеспечивают реализацию. + + [1]: http://dev.w3.org/geo/api/spec-source.html + +**Предупреждение**: сбор и использование данных геопозиционирования поднимает вопросы важные конфиденциальности. Политика конфиденциальности вашего приложения должна обсудить, как приложение использует данные геопозиционирования, ли она совместно с другими сторонами и уровень точности данных (например, грубый, тонкий, почтовый индекс уровня, т.д.). Геолокации, как правило, считается конфиденциальной, потому, что она может выявить местонахождение пользователя и, если сохранены, история их путешествия. Таким образом помимо политики конфиденциальности приложения, следует решительно рассмотреть уведомления just-in-time, прежде чем приложение обращается к геолокации (если операционной системы устройства не так уже). Это уведомление должно обеспечивать ту же информацию, отметили выше, а также получения разрешения пользователя (например, путем представления выбора **OK** и **Нет, спасибо**). Для получения дополнительной информации пожалуйста, смотрите в руководстве конфиденциальности. + +## Установка + + cordova plugin add cordova-plugin-geolocation + + +## Поддерживаемые платформы + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Firefox OS +* iOS +* Tizen +* Windows Phone 7 и 8 +* Windows 8 + +## Методы + +* navigator.geolocation.getCurrentPosition +* navigator.geolocation.watchPosition +* navigator.geolocation.clearWatch + +## Объекты (только для чтения) + +* Position +* PositionError +* Coordinates + +## navigator.geolocation.getCurrentPosition + +Возвращает текущее положение устройства для `geolocationSuccess` обратного вызова с `Position` объект в качестве параметра. Если есть ошибка, `geolocationError` обратного вызова передается `PositionError` объект. + + navigator.geolocation.getCurrentPosition (geolocationSuccess, [geolocationError], [geolocationOptions]); + + +### Параметры + +* **geolocationSuccess**: обратный вызов, который передается в текущей позиции. + +* **geolocationError**: *(необязательно)* обратного вызова, который выполняется при возникновении ошибки. + +* **geolocationOptions**: *(необязательно)* параметры геопозиционирования. + +### Пример + + onSuccess обратного вызова / / этот метод принимает позицию объекта, который содержит / / текущие GPS координаты / / var onSuccess = function(position) {alert (' Широта: ' + position.coords.latitude + «\n» + ' Долгота: ' + position.coords.longitude + «\n» + ' Высота: ' + position.coords.altitude + «\n» + ' точность: ' + position.coords.accuracy + «\n» + ' высоте точность: ' + position.coords.altitudeAccuracy + «\n» + ' заголовок: ' + position.coords.heading + «\n» + ' скорость: ' + position.coords.speed + «\n» + ' штампа времени: ' + position.timestamp + «\n»);}; + + onError обратного вызова получает объект PositionError / / функция onError(error) {alert (' код: ' + error.code + «\n» + ' сообщение: ' + error.message + «\n»);} + + navigator.geolocation.getCurrentPosition (onSuccess, onError); + + +## navigator.geolocation.watchPosition + +Возвращает текущее положение устройства при обнаружении изменения в позиции. Когда устройство получает новое место, `geolocationSuccess` обратного вызова выполняется с `Position` объект в качестве параметра. Если есть ошибка, `geolocationError` обратного вызова выполняется с `PositionError` объект в качестве параметра. + + var watchId = navigator.geolocation.watchPosition (geolocationSuccess, [geolocationError], [geolocationOptions]); + + +### Параметры + +* **geolocationSuccess**: обратный вызов, который передается в текущей позиции. + +* **geolocationError**: (необязательно) обратного вызова, который выполняется при возникновении ошибки. + +* **geolocationOptions**: параметры (необязательно) географического расположения. + +### Возвращает + +* **Строка**: Возвращает идентификатор часы, ссылается на позицию интервала часы. Идентификатор часы должны использоваться с `navigator.geolocation.clearWatch` прекратить слежение за изменением в положении. + +### Пример + + onSuccess обратного вызова / / этот метод принимает «Position» объект, который содержит / / текущие GPS координаты / / функция onSuccess(position) {var элемент = document.getElementById('geolocation'); + element.innerHTML = ' Широта: ' + position.coords.latitude + ' < br / >' + ' Долгота: ' + position.coords.longitude + ' < br / >' + ' < hr / >' + element.innerHTML; + } / / onError обратного вызова получает объект PositionError / / функция onError(error) {alert (' код: ' + error.code + «\n» + ' сообщение: ' + error.message + «\n»);} + + Опции: Бросьте сообщение об ошибке, если обновление не получено каждые 30 секунд. + var watchID = navigator.geolocation.watchPosition (onSuccess, onError, {тайм-аут: 30000}); + + +## geolocationOptions + +Необязательные параметры для настройки поиска географического расположения`Position`. + + {maximumAge: 3000, тайм-аут: 5000, enableHighAccuracy: true}; + + +### Параметры + +* **enableHighAccuracy**: предоставляет подсказку, что приложению требуются наилучшие результаты. По умолчанию устройство пытается получить `Position` с использованием методов на основе сети. Установка этого свойства значение `true` указывает среде использовать более точные методы, например спутникового позиционирования. *(Логическое значение)* + +* **время ожидания**: максимальная длина времени (в миллисекундах), которое может пройти от вызова `navigator.geolocation.getCurrentPosition` или `geolocation.watchPosition` до соответствующих `geolocationSuccess` выполняет обратный вызов. Если `geolocationSuccess` обратного вызова не вызывается в течение этого времени, `geolocationError` обратного вызова передается `PositionError.TIMEOUT` код ошибки. (Обратите внимание, что при использовании в сочетании с `geolocation.watchPosition` , `geolocationError` обратный вызов может быть вызван на интервале каждые `timeout` миллисекунд!) *(Число)* + +* **maximumAge**: принять кэшированное положение, возраст которых не превышает указанного времени в миллисекундах. *(Число)* + +### Особенности Android + +Эмуляторы Android 2.x не возвращать результат географического расположения, если `enableHighAccuracy` параметр имеет значение`true`. + +## navigator.geolocation.clearWatch + +Остановить просмотр для изменения местоположения устройства ссылается `watchID` параметр. + + navigator.geolocation.clearWatch(watchID); + + +### Параметры + +* **watchID**: идентификатор `watchPosition` интервал, чтобы очистить. (Строка) + +### Пример + + Опции: наблюдать за изменениями в положении и использовать наиболее / / точная позиция приобретение доступным методом. + var watchID = navigator.geolocation.watchPosition (onSuccess, onError, {enableHighAccuracy: true}); + + .. .later на... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +Содержит `Position` координат и отметок времени, созданная API геопозиционирования. + +### Параметры + +* **CoOrds**: набор географических координат. *(Координаты)* + +* **штамп времени**: штамп времени создания для `coords` . *(Дата)* + +## Coordinates + +A `Coordinates` объект присоединен к `Position` объект, который доступен для обратного вызова функций в запросы для текущей позиции. Он содержит набор свойств, которые описывают географические координаты позиции. + +### Параметры + +* **Широта**: Широта в десятичных градусах. *(Число)* + +* **Долгота**: Долгота в десятичных градусах. *(Число)* + +* **Высота**: высота позиции в метрах над эллипсоидом. *(Число)* + +* **точность**: уровень точности координат широты и долготы в метрах. *(Число)* + +* **altitudeAccuracy**: уровень точности координат высоты в метрах. *(Число)* + +* **заголовок**: направление движения, указанный в градусах, считая по часовой стрелке относительно истинного севера. *(Число)* + +* **скорость**: Текущая скорость земли устройства, указанного в метрах в секунду. *(Число)* + +### Особенности Amazon Fire OS + +**altitudeAccuracy**: не поддерживается Android устройств, возвращая`null`. + +### Особенности Android + +**altitudeAccuracy**: не поддерживается Android устройств, возвращая`null`. + +## PositionError + +`PositionError`Объект передается в `geolocationError` функции обратного вызова при возникновении ошибки с navigator.geolocation. + +### Параметры + +* **code**: один из стандартных кодов ошибок, перечисленных ниже. + +* **сообщение**: сообщение об ошибке с подробными сведениями об ошибке. + +### Константы + +* `PositionError.PERMISSION_DENIED` + * Возвращается, когда пользователи не позволяют приложению получить сведения о положении. Это зависит от платформы. +* `PositionError.POSITION_UNAVAILABLE` + * Возвращается, если устройство не удается получить позиции. В общем это означает, что прибор не подключен к сети или не может получить Спутниковое исправить. +* `PositionError.TIMEOUT` + * Возвращается, если устройство не удается получить позиции в течение времени, заданного параметром `timeout` в `geolocationOptions` . При использовании с `navigator.geolocation.watchPosition` , эта ошибка может быть неоднократно передан `geolocationError` обратного вызова каждый `timeout` миллисекунд. diff --git a/plugins/cordova-plugin-geolocation/doc/zh/README.md b/plugins/cordova-plugin-geolocation/doc/zh/README.md new file mode 100644 index 0000000..b2afea5 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/doc/zh/README.md @@ -0,0 +1,268 @@ + + +# cordova-plugin-geolocation + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-geolocation.svg)](https://travis-ci.org/apache/cordova-plugin-geolocation) + +這個外掛程式提供了有關該設備的位置,例如緯度和經度資訊。 常見的位置資訊來源包括全球定位系統 (GPS) 和網路信號,如 IP 位址、 RFID、 WiFi 和藍牙 MAC 位址和 GSM/CDMA 儲存格 Id 從推斷出的位置。 沒有任何保證,API 返回設備的實際位置。 + +此 API 基於[W3C 地理定位 API 規範](http://dev.w3.org/geo/api/spec-source.html),並只執行已經不提供實現的設備上。 + +**警告**: 地理定位資料的收集和使用提出了重要的隱私問題。 您的應用程式的隱私權原則應該討論這款應用程式如何使用地理定位資料,資料是否共用它的任何其他締約方和的資料 (例如,粗、 細,ZIP 代碼級別,等等) 的精度水準。 地理定位資料一般認為是敏感,因為它能揭示使用者的下落以及如果存儲,他們的旅行的歷史。 因此,除了應用程式的隱私權原則,您應強烈考慮之前應用程式訪問地理定位資料 (如果設備作業系統不會這樣做已經) 提供在時間的通知。 該通知應提供相同的資訊上文指出的並獲取該使用者的許可權 (例如,通過為**確定**並**不感謝**提出的選擇)。 有關詳細資訊,請參閱隱私指南。 + +這個外掛程式定義了一個全球 `navigator.geolocation` 物件 (為平臺哪裡否則丟失)。 + +儘管物件是在全球範圍內,提供這個外掛程式的功能不可用直到 `deviceready` 事件之後。 + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + + +## 安裝 + +這就要求科爾多瓦 5.0 + (當前穩定 v1.0.0) + + cordova plugin add cordova-plugin-geolocation + + +舊版本的科爾多瓦仍可以通過已棄用 id (陳舊 0.3.12) 安裝 + + cordova plugin add org.apache.cordova.geolocation + + +它也是可以直接通過回購 url 安裝 (不穩定) + + cordova plugin add https://github.com/apache/cordova-plugin-geolocation.git + + +## 支援的平臺 + + * 亞馬遜火 OS + * Android 系統 + * 黑莓 10 + * 火狐瀏覽器作業系統 + * iOS + * Tizen + * Windows Phone 7 和 8 + * Windows 8 + * Windows + +## 方法 + + * navigator.geolocation.getCurrentPosition + * navigator.geolocation.watchPosition + * navigator.geolocation.clearWatch + +## 物件 (唯讀) + + * Position + * PositionError + * Coordinates + +## navigator.geolocation.getCurrentPosition + +返回設備的當前位置到 `geolocationSuccess` 回檔與 `Position` 物件作為參數。 如果有錯誤,`geolocationError` 回檔傳遞一個 `PositionError` 物件。 + + navigator.geolocation.getCurrentPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### 參數 + + * **geolocationSuccess**: 傳遞當前位置的回檔。 + + * **geolocationError**: *(可選)*如果錯誤發生時執行的回檔。 + + * **geolocationOptions**: *(可選)*地理定位選項。 + +### 示例 + + // 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'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + + +## navigator.geolocation.watchPosition + +返回設備的當前的位置,當檢測到更改位置。 當設備檢索一個新位置時,則 `geolocationSuccess` 回檔執行與 `Position` 物件作為參數。 如果有錯誤,則 `geolocationError` 回檔執行同一個 `PositionError` 物件作為參數。 + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### 參數 + + * **geolocationSuccess**: 傳遞當前位置的回檔。 + + * **geolocationError**: (可選) 如果錯誤發生時執行的回檔。 + + * **geolocationOptions**: (可選) 地理定位選項。 + +### 返回 + + * **String**: 返回引用的觀看位置間隔的表 id。 應與一起使用的表 id `navigator.geolocation.clearWatch` 停止了觀看中位置的更改。 + +### 示例 + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '
' + + 'Longitude: ' + position.coords.longitude + '
' + + '
' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +若要自訂的地理 `Position` 檢索的可選參數. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### 選項 + + * **enableHighAccuracy**: 提供應用程式需要最佳的可能結果的提示。 預設情況下,該設備將嘗試檢索 `Position` 使用基於網路的方法。 將此屬性設置為 `true` 告訴要使用更精確的方法,如衛星定位的框架。 *(布林值)* + + * **timeout**: 時間 (毫秒) 從調用傳遞,允許的最大長度 `navigator.geolocation.getCurrentPosition` 或 `geolocation.watchPosition` 直到相應的 `geolocationSuccess` 回檔執行。 如果 `geolocationSuccess` 不會在此時間內調用回檔 `geolocationError` 傳遞回檔 `PositionError.TIMEOUT` 錯誤代碼。 (請注意,與一起使用時 `geolocation.watchPosition` 、 `geolocationError` 的時間間隔可以調用回檔每 `timeout` 毫秒!)*(人數)* + + * **maximumAge**: 接受其年齡大於指定以毫秒為單位的時間沒有緩存的位置。*(人數)* + +### Android 的怪癖 + +Android 2.x 模擬器不除非 `enableHighAccuracy` 選項設置為 `true`,否則返回地理定位結果. + +## navigator.geolocation.clearWatch + +停止觀察到 `watchID` 參數所引用的設備的位置。 + + navigator.geolocation.clearWatch(watchID); + + +### 參數 + + * **watchID**: 的 id `watchPosition` 清除的時間間隔。(字串) + +### 示例 + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +包含 `Position` 座標和時間戳記,由地理位置 API 創建。 + +### 屬性 + + * **coords**: 一組的地理座標。*(座標)* + + * **timestamp**: 創建時間戳記為 `coords` 。*(DOMTimeStamp)* + +## Coordinates + +`Coordinates` 的物件附加到一個 `Position` 物件,可用於在當前職位的請求中的回呼函數。 它包含一組屬性描述位置的地理座標。 + +### 屬性 + + * **latitude**: 緯度以十進位度為單位。*(人數)* + + * **longitude**: 經度以十進位度為單位。*(人數)* + + * **altitude**: 高度在米以上橢球體中的位置。*(人數)* + + * **accuracy**: 中米的緯度和經度座標的精度級別。*(人數)* + + * **altitudeAccuracy**: 在米的海拔高度座標的精度級別。*(人數)* + + * **heading**: 旅行,指定以度為單位元數目相對於真北順時針方向。*(人數)* + + * **speed**: 當前地面速度的設備,指定在米每秒。*(人數)* + +### 亞馬遜火 OS 怪癖 + +**altitudeAccuracy**: 不支援的 Android 設備,返回 `null`. + +### Android 的怪癖 + +**altitudeAccuracy**: 不支援的 Android 設備,返回 `null`. + +## PositionError + +`PositionError` 物件將傳遞給 `geolocationError` 回呼函數中,當出現 navigator.geolocation 錯誤時發生。 + +### 屬性 + + * **code**: 下面列出的預定義的錯誤代碼之一。 + + * **message**: 描述所遇到的錯誤的詳細資訊的錯誤訊息。 + +### 常量 + + * `PositionError.PERMISSION_DENIED` + * 返回當使用者不允許應用程式檢索的位置資訊。這是取決於平臺。 + * `PositionError.POSITION_UNAVAILABLE` + * 返回設備時,不能檢索的位置。一般情況下,這意味著該設備未連接到網路或無法獲取衛星的修復。 + * `PositionError.TIMEOUT` + * 返回設備時,無法在指定的時間內檢索位置 `timeout` 中包含 `geolocationOptions` 。 與一起使用時 `navigator.geolocation.watchPosition` ,此錯誤可能反復傳遞給 `geolocationError` 回檔每 `timeout` 毫秒為單位)。 \ No newline at end of file diff --git a/plugins/cordova-plugin-geolocation/doc/zh/index.md b/plugins/cordova-plugin-geolocation/doc/zh/index.md new file mode 100644 index 0000000..c78a9f7 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/doc/zh/index.md @@ -0,0 +1,255 @@ + + +# cordova-plugin-geolocation + +這個外掛程式提供了有關該設備的位置,例如緯度和經度資訊。 常見的位置資訊來源包括全球定位系統 (GPS) 和網路信號,如 IP 位址、 RFID、 WiFi 和藍牙 MAC 位址和 GSM/CDMA 儲存格 Id 從推斷出的位置。 沒有任何保證,API 返回設備的實際位置。 + +此 API 基於[W3C 地理定位 API 規範][1],並只執行已經不提供實現的設備上。 + + [1]: http://dev.w3.org/geo/api/spec-source.html + +**警告**: 地理定位資料的收集和使用提出了重要的隱私問題。 您的應用程式的隱私權原則應該討論這款應用程式如何使用地理定位資料,資料是否共用它的任何其他締約方和的資料 (例如,粗、 細,ZIP 代碼級別,等等) 的精度水準。 地理定位資料一般認為是敏感,因為它能揭示使用者的下落以及如果存儲,他們的旅行的歷史。 因此,除了應用程式的隱私權原則,您應強烈考慮之前應用程式訪問地理定位資料 (如果設備作業系統不會這樣做已經) 提供在時間的通知。 該通知應提供相同的資訊上文指出的並獲取該使用者的許可權 (例如,通過為**確定**並**不感謝**提出的選擇)。 有關詳細資訊,請參閱隱私指南。 + +這個外掛程式定義了一個全球 `navigator.geolocation` 物件 (為平臺哪裡否則丟失)。 + +儘管物件是在全球範圍內,提供這個外掛程式的功能不可用直到 `deviceready` 事件之後。 + + document.addEventListener("deviceready", onDeviceReady, false); + function onDeviceReady() { + console.log("navigator.geolocation works well"); + } + + +## 安裝 + + cordova plugin add cordova-plugin-geolocation + + +## 支援的平臺 + +* 亞馬遜火 OS +* Android 系統 +* 黑莓 10 +* 火狐瀏覽器作業系統 +* iOS +* Tizen +* Windows Phone 7 和 8 +* Windows 8 + +## 方法 + +* navigator.geolocation.getCurrentPosition +* navigator.geolocation.watchPosition +* navigator.geolocation.clearWatch + +## 物件 (唯讀) + +* Position +* PositionError +* Coordinates + +## navigator.geolocation.getCurrentPosition + +返回設備的當前位置到 `geolocationSuccess` 回檔與 `Position` 物件作為參數。 如果有錯誤,`geolocationError` 回檔傳遞一個 `PositionError` 物件。 + + navigator.geolocation.getCurrentPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### 參數 + +* **geolocationSuccess**: 傳遞當前位置的回檔。 + +* **geolocationError**: *(可選)*如果錯誤發生時執行的回檔。 + +* **geolocationOptions**: *(可選)*地理定位選項。 + +### 示例 + + // 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'); + }; + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + navigator.geolocation.getCurrentPosition(onSuccess, onError); + + +## navigator.geolocation.watchPosition + +返回設備的當前的位置,當檢測到更改位置。 當設備檢索一個新位置時,則 `geolocationSuccess` 回檔執行與 `Position` 物件作為參數。 如果有錯誤,則 `geolocationError` 回檔執行同一個 `PositionError` 物件作為參數。 + + var watchId = navigator.geolocation.watchPosition(geolocationSuccess, + [geolocationError], + [geolocationOptions]); + + +### 參數 + +* **geolocationSuccess**: 傳遞當前位置的回檔。 + +* **geolocationError**: (可選) 如果錯誤發生時執行的回檔。 + +* **geolocationOptions**: (可選) 地理定位選項。 + +### 返回 + +* **String**: 返回引用的觀看位置間隔的表 id。 應與一起使用的表 id `navigator.geolocation.clearWatch` 停止了觀看中位置的更改。 + +### 示例 + + // onSuccess Callback + // This method accepts a `Position` object, which contains + // the current GPS coordinates + // + function onSuccess(position) { + var element = document.getElementById('geolocation'); + element.innerHTML = 'Latitude: ' + position.coords.latitude + '
' + + 'Longitude: ' + position.coords.longitude + '
' + + '
' + element.innerHTML; + } + + // onError Callback receives a PositionError object + // + function onError(error) { + alert('code: ' + error.code + '\n' + + 'message: ' + error.message + '\n'); + } + + // Options: throw an error if no update is received every 30 seconds. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); + + +## geolocationOptions + +若要自訂的地理 `Position` 檢索的可選參數. + + { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }; + + +### 選項 + +* **enableHighAccuracy**: 提供應用程式需要最佳的可能結果的提示。 預設情況下,該設備將嘗試檢索 `Position` 使用基於網路的方法。 將此屬性設置為 `true` 告訴要使用更精確的方法,如衛星定位的框架。 *(布林值)* + +* **timeout**: 時間 (毫秒) 從調用傳遞,允許的最大長度 `navigator.geolocation.getCurrentPosition` 或 `geolocation.watchPosition` 直到相應的 `geolocationSuccess` 回檔執行。 如果 `geolocationSuccess` 不會在此時間內調用回檔 `geolocationError` 傳遞回檔 `PositionError.TIMEOUT` 錯誤代碼。 (請注意,與一起使用時 `geolocation.watchPosition` 、 `geolocationError` 的時間間隔可以調用回檔每 `timeout` 毫秒!)*(人數)* + +* **maximumAge**: 接受其年齡大於指定以毫秒為單位的時間沒有緩存的位置。*(人數)* + +### Android 的怪癖 + +Android 2.x 模擬器不除非 `enableHighAccuracy` 選項設置為 `true`,否則返回地理定位結果. + +## navigator.geolocation.clearWatch + +停止觀察到 `watchID` 參數所引用的設備的位置。 + + navigator.geolocation.clearWatch(watchID); + + +### 參數 + +* **watchID**: 的 id `watchPosition` 清除的時間間隔。(字串) + +### 示例 + + // Options: watch for changes in position, and use the most + // accurate position acquisition method available. + // + var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true }); + + // ...later on... + + navigator.geolocation.clearWatch(watchID); + + +## Position + +包含 `Position` 座標和時間戳記,由地理位置 API 創建。 + +### 屬性 + +* **coords**: 一組的地理座標。*(座標)* + +* **timestamp**: 創建時間戳記為 `coords` 。*(DOMTimeStamp)* + +## Coordinates + +`Coordinates` 的物件附加到一個 `Position` 物件,可用於在當前職位的請求中的回呼函數。 它包含一組屬性描述位置的地理座標。 + +### 屬性 + +* **latitude**: 緯度以十進位度為單位。*(人數)* + +* **longitude**: 經度以十進位度為單位。*(人數)* + +* **altitude**: 高度在米以上橢球體中的位置。*(人數)* + +* **accuracy**: 中米的緯度和經度座標的精度級別。*(人數)* + +* **altitudeAccuracy**: 在米的海拔高度座標的精度級別。*(人數)* + +* **heading**: 旅行,指定以度為單位元數目相對於真北順時針方向。*(人數)* + +* **speed**: 當前地面速度的設備,指定在米每秒。*(人數)* + +### 亞馬遜火 OS 怪癖 + +**altitudeAccuracy**: 不支援的 Android 設備,返回 `null`. + +### Android 的怪癖 + +**altitudeAccuracy**: 不支援的 Android 設備,返回 `null`. + +## PositionError + +`PositionError` 物件將傳遞給 `geolocationError` 回呼函數中,當出現 navigator.geolocation 錯誤時發生。 + +### 屬性 + +* **code**: 下面列出的預定義的錯誤代碼之一。 + +* **message**: 描述所遇到的錯誤的詳細資訊的錯誤訊息。 + +### 常量 + +* `PositionError.PERMISSION_DENIED` + * 返回當使用者不允許應用程式檢索的位置資訊。這是取決於平臺。 +* `PositionError.POSITION_UNAVAILABLE` + * 返回設備時,不能檢索的位置。一般情況下,這意味著該設備未連接到網路或無法獲取衛星的修復。 +* `PositionError.TIMEOUT` + * 返回設備時,無法在指定的時間內檢索位置 `timeout` 中包含 `geolocationOptions` 。 與一起使用時 `navigator.geolocation.watchPosition` ,此錯誤可能反復傳遞給 `geolocationError` 回檔每 `timeout` 毫秒為單位)。 diff --git a/plugins/cordova-plugin-geolocation/package.json b/plugins/cordova-plugin-geolocation/package.json new file mode 100644 index 0000000..4fb1854 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/package.json @@ -0,0 +1,141 @@ +{ + "_args": [ + [ + { + "raw": "cordova-plugin-geolocation", + "scope": null, + "escapedName": "cordova-plugin-geolocation", + "name": "cordova-plugin-geolocation", + "rawSpec": "", + "spec": "latest", + "type": "tag" + }, + "D:\\pWork\\yunkong2.vis.cordova\\node_modules" + ] + ], + "_from": "cordova-plugin-geolocation@latest", + "_id": "cordova-plugin-geolocation@2.4.3", + "_inCache": true, + "_location": "/cordova-plugin-geolocation", + "_nodeVersion": "6.10.1", + "_npmOperationalInternal": { + "host": "packages-12-west.internal.npmjs.com", + "tmp": "tmp/cordova-plugin-geolocation-2.4.3.tgz_1493685640809_0.01689610001631081" + }, + "_npmUser": { + "name": "filmaj", + "email": "maj.fil@gmail.com" + }, + "_npmVersion": "3.10.10", + "_phantomChildren": {}, + "_requested": { + "raw": "cordova-plugin-geolocation", + "scope": null, + "escapedName": "cordova-plugin-geolocation", + "name": "cordova-plugin-geolocation", + "rawSpec": "", + "spec": "latest", + "type": "tag" + }, + "_requiredBy": [ + "#USER" + ], + "_resolved": "https://registry.npmjs.org/cordova-plugin-geolocation/-/cordova-plugin-geolocation-2.4.3.tgz", + "_shasum": "1dd00023d1f1a2ce330f8767ed08f7b738fe7184", + "_shrinkwrap": null, + "_spec": "cordova-plugin-geolocation", + "_where": "D:\\pWork\\yunkong2.vis.cordova\\node_modules", + "author": { + "name": "Apache Software Foundation" + }, + "bugs": { + "url": "https://github.com/apache/cordova-plugin-geolocation/issues" + }, + "cordova": { + "id": "cordova-plugin-geolocation", + "platforms": [ + "android", + "amazon-fireos", + "ios", + "blackberry10", + "ubuntu", + "wp7", + "wp8", + "windows8", + "windows", + "firefoxos" + ] + }, + "dependencies": {}, + "description": "Cordova Geolocation Plugin", + "devDependencies": { + "jshint": "^2.6.0" + }, + "directories": {}, + "dist": { + "shasum": "1dd00023d1f1a2ce330f8767ed08f7b738fe7184", + "tarball": "https://registry.npmjs.org/cordova-plugin-geolocation/-/cordova-plugin-geolocation-2.4.3.tgz" + }, + "engines": { + "cordovaDependencies": { + "3.0.0": { + "cordova": ">100" + } + } + }, + "homepage": "https://github.com/apache/cordova-plugin-geolocation#readme", + "keywords": [ + "cordova", + "geolocation", + "ecosystem:cordova", + "cordova-android", + "cordova-amazon-fireos", + "cordova-ios", + "cordova-blackberry10", + "cordova-ubuntu", + "cordova-wp7", + "cordova-wp8", + "cordova-windows8", + "cordova-windows", + "cordova-firefoxos" + ], + "license": "Apache-2.0", + "maintainers": [ + { + "name": "bowserj", + "email": "bowserj@apache.org" + }, + { + "name": "csantanapr", + "email": "csantana23@gmail.com" + }, + { + "name": "filmaj", + "email": "maj.fil@gmail.com" + }, + { + "name": "purplecabbage", + "email": "purplecabbage@gmail.com" + }, + { + "name": "shazron", + "email": "shazron@gmail.com" + }, + { + "name": "stevegill", + "email": "stevengill97@gmail.com" + } + ], + "name": "cordova-plugin-geolocation", + "optionalDependencies": {}, + "readme": "ERROR: No README data found!", + "repository": { + "type": "git", + "url": "git+https://github.com/apache/cordova-plugin-geolocation.git" + }, + "scripts": { + "jshint": "node node_modules/jshint/bin/jshint www && node node_modules/jshint/bin/jshint src && node node_modules/jshint/bin/jshint tests", + "test": "npm run jshint" + }, + "version": "2.4.3" +} diff --git a/plugins/cordova-plugin-geolocation/plugin.xml b/plugins/cordova-plugin-geolocation/plugin.xml new file mode 100644 index 0000000..9112867 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/plugin.xml @@ -0,0 +1,269 @@ + + + + + + Geolocation + Cordova Geolocation Plugin + Apache 2.0 + cordova,geolocation + https://git-wip-us.apache.org/repos/asf/cordova-plugin-geolocation.git + https://issues.apache.org/jira/browse/CB/component/12320638 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + $GEOLOCATION_USAGE_DESCRIPTION + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + read_geolocation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/cordova-plugin-geolocation/src/android/Geolocation.java b/plugins/cordova-plugin-geolocation/src/android/Geolocation.java new file mode 100644 index 0000000..6452170 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/src/android/Geolocation.java @@ -0,0 +1,107 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + + +package org.apache.cordova.geolocation; + +import android.content.pm.PackageManager; +import android.Manifest; +import android.os.Build; + +import org.apache.cordova.CallbackContext; +import org.apache.cordova.CordovaArgs; +import org.apache.cordova.CordovaPlugin; +import org.apache.cordova.PermissionHelper; +import org.apache.cordova.PluginResult; +import org.apache.cordova.LOG; +import org.json.JSONArray; +import org.json.JSONException; + +import javax.security.auth.callback.Callback; + +public class Geolocation extends CordovaPlugin { + + String TAG = "GeolocationPlugin"; + CallbackContext context; + + String [] permissions = { Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION }; + + + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { + LOG.d(TAG, "We are entering execute"); + context = callbackContext; + if(action.equals("getPermission")) + { + if(hasPermisssion()) + { + PluginResult r = new PluginResult(PluginResult.Status.OK); + context.sendPluginResult(r); + return true; + } + else { + PermissionHelper.requestPermissions(this, 0, permissions); + } + return true; + } + return false; + } + + + public void onRequestPermissionResult(int requestCode, String[] permissions, + int[] grantResults) throws JSONException + { + PluginResult result; + //This is important if we're using Cordova without using Cordova, but we have the geolocation plugin installed + if(context != null) { + for (int r : grantResults) { + if (r == PackageManager.PERMISSION_DENIED) { + LOG.d(TAG, "Permission Denied!"); + result = new PluginResult(PluginResult.Status.ILLEGAL_ACCESS_EXCEPTION); + context.sendPluginResult(result); + return; + } + + } + result = new PluginResult(PluginResult.Status.OK); + context.sendPluginResult(result); + } + } + + public boolean hasPermisssion() { + for(String p : permissions) + { + if(!PermissionHelper.hasPermission(this, p)) + { + return false; + } + } + return true; + } + + /* + * We override this so that we can access the permissions variable, which no longer exists in + * the parent class, since we can't initialize it reliably in the constructor! + */ + + public void requestPermissions(int requestCode) + { + PermissionHelper.requestPermissions(this, requestCode, permissions); + } + + + +} diff --git a/plugins/cordova-plugin-geolocation/src/firefoxos/GeolocationProxy.js b/plugins/cordova-plugin-geolocation/src/firefoxos/GeolocationProxy.js new file mode 100644 index 0000000..e4b4052 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/src/firefoxos/GeolocationProxy.js @@ -0,0 +1,67 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +// latest geolocation spec can be found here: http://www.w3.org/TR/geolocation-API/ + +var idsMap = {}; + +module.exports = { + getLocation: function(success, error, args) { + var geo = cordova.require('cordova/modulemapper').getOriginalSymbol(window, 'navigator.geolocation'); + function successCallback(position) { + // Cordova is creating Position object using just coords + success(position.coords); + } + geo.getCurrentPosition(successCallback, error, { + enableHighAccuracy: args[0], + maximumAge: args[1] + }); + }, + + addWatch: function(success, error, args) { + var geo = cordova.require('cordova/modulemapper').getOriginalSymbol(window, 'navigator.geolocation'); + var id = args[0]; + function successCallback(position) { + success(position.coords); + } + var nativeId = geo.watchPosition(successCallback, error, { + enableHighAccuracy: args[1] + }); + + idsMap[id] = nativeId; + }, + + clearWatch: function(success, error, args) { + var geo = cordova.require('cordova/modulemapper').getOriginalSymbol(window, 'navigator.geolocation'); + var id = args[0]; + + if(id in idsMap) { + geo.clearWatch(idsMap[id]); + delete idsMap[id]; + } + + if(success) { + success(); + } + } +}; + +require("cordova/exec/proxy").add("Geolocation", module.exports); diff --git a/plugins/cordova-plugin-geolocation/src/ios/CDVLocation.h b/plugins/cordova-plugin-geolocation/src/ios/CDVLocation.h new file mode 100644 index 0000000..cce2738 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/src/ios/CDVLocation.h @@ -0,0 +1,70 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#import +#import +#import + +enum CDVLocationStatus { + PERMISSIONDENIED = 1, + POSITIONUNAVAILABLE, + TIMEOUT +}; +typedef NSUInteger CDVLocationStatus; + +// simple object to keep track of location information +@interface CDVLocationData : NSObject { + CDVLocationStatus locationStatus; + NSMutableArray* locationCallbacks; + NSMutableDictionary* watchCallbacks; + CLLocation* locationInfo; +} + +@property (nonatomic, assign) CDVLocationStatus locationStatus; +@property (nonatomic, strong) CLLocation* locationInfo; +@property (nonatomic, strong) NSMutableArray* locationCallbacks; +@property (nonatomic, strong) NSMutableDictionary* watchCallbacks; + +@end + +@interface CDVLocation : CDVPlugin { + @private BOOL __locationStarted; + @private BOOL __highAccuracyEnabled; + CDVLocationData* locationData; +} + +@property (nonatomic, strong) CLLocationManager* locationManager; +@property (nonatomic, strong) CDVLocationData* locationData; + +- (void)getLocation:(CDVInvokedUrlCommand*)command; +- (void)addWatch:(CDVInvokedUrlCommand*)command; +- (void)clearWatch:(CDVInvokedUrlCommand*)command; +- (void)returnLocationInfo:(NSString*)callbackId andKeepCallback:(BOOL)keepCallback; +- (void)returnLocationError:(NSUInteger)errorCode withMessage:(NSString*)message; +- (void)startLocation:(BOOL)enableHighAccuracy; + +- (void)locationManager:(CLLocationManager*)manager + didUpdateToLocation:(CLLocation*)newLocation + fromLocation:(CLLocation*)oldLocation; + +- (void)locationManager:(CLLocationManager*)manager + didFailWithError:(NSError*)error; + +- (BOOL)isLocationServicesEnabled; +@end diff --git a/plugins/cordova-plugin-geolocation/src/ios/CDVLocation.m b/plugins/cordova-plugin-geolocation/src/ios/CDVLocation.m new file mode 100644 index 0000000..26802d6 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/src/ios/CDVLocation.m @@ -0,0 +1,365 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#import "CDVLocation.h" + +#pragma mark Constants + +#define kPGLocationErrorDomain @"kPGLocationErrorDomain" +#define kPGLocationDesiredAccuracyKey @"desiredAccuracy" +#define kPGLocationForcePromptKey @"forcePrompt" +#define kPGLocationDistanceFilterKey @"distanceFilter" +#define kPGLocationFrequencyKey @"frequency" + +#pragma mark - +#pragma mark Categories + +@implementation CDVLocationData + +@synthesize locationStatus, locationInfo, locationCallbacks, watchCallbacks; +- (CDVLocationData*)init +{ + self = (CDVLocationData*)[super init]; + if (self) { + self.locationInfo = nil; + self.locationCallbacks = nil; + self.watchCallbacks = nil; + } + return self; +} + +@end + +#pragma mark - +#pragma mark CDVLocation + +@implementation CDVLocation + +@synthesize locationManager, locationData; + +- (void)pluginInitialize +{ + self.locationManager = [[CLLocationManager alloc] init]; + self.locationManager.delegate = self; // Tells the location manager to send updates to this object + __locationStarted = NO; + __highAccuracyEnabled = NO; + self.locationData = nil; +} + +- (BOOL)isAuthorized +{ + BOOL authorizationStatusClassPropertyAvailable = [CLLocationManager respondsToSelector:@selector(authorizationStatus)]; // iOS 4.2+ + + if (authorizationStatusClassPropertyAvailable) { + NSUInteger authStatus = [CLLocationManager authorizationStatus]; +#ifdef __IPHONE_8_0 + if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) { //iOS 8.0+ + return (authStatus == kCLAuthorizationStatusAuthorizedWhenInUse) || (authStatus == kCLAuthorizationStatusAuthorizedAlways) || (authStatus == kCLAuthorizationStatusNotDetermined); + } +#endif + return (authStatus == kCLAuthorizationStatusAuthorizedAlways) || (authStatus == kCLAuthorizationStatusNotDetermined); + } + + // by default, assume YES (for iOS < 4.2) + return YES; +} + +- (BOOL)isLocationServicesEnabled +{ + BOOL locationServicesEnabledInstancePropertyAvailable = [self.locationManager respondsToSelector:@selector(locationServicesEnabled)]; // iOS 3.x + BOOL locationServicesEnabledClassPropertyAvailable = [CLLocationManager respondsToSelector:@selector(locationServicesEnabled)]; // iOS 4.x + + if (locationServicesEnabledClassPropertyAvailable) { // iOS 4.x + return [CLLocationManager locationServicesEnabled]; + } else { + return NO; + } +} + +- (void)startLocation:(BOOL)enableHighAccuracy +{ + if (![self isLocationServicesEnabled]) { + [self returnLocationError:PERMISSIONDENIED withMessage:@"Location services are not enabled."]; + return; + } + if (![self isAuthorized]) { + NSString* message = nil; + BOOL authStatusAvailable = [CLLocationManager respondsToSelector:@selector(authorizationStatus)]; // iOS 4.2+ + if (authStatusAvailable) { + NSUInteger code = [CLLocationManager authorizationStatus]; + if (code == kCLAuthorizationStatusNotDetermined) { + // could return POSITION_UNAVAILABLE but need to coordinate with other platforms + message = @"User undecided on application's use of location services."; + } else if (code == kCLAuthorizationStatusRestricted) { + message = @"Application's use of location services is restricted."; + } + } + // PERMISSIONDENIED is only PositionError that makes sense when authorization denied + [self returnLocationError:PERMISSIONDENIED withMessage:message]; + + return; + } + +#ifdef __IPHONE_8_0 + NSUInteger code = [CLLocationManager authorizationStatus]; + if (code == kCLAuthorizationStatusNotDetermined && ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)] || [self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])) { //iOS8+ + __highAccuracyEnabled = enableHighAccuracy; + if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"]){ + [self.locationManager requestWhenInUseAuthorization]; + } else if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationAlwaysUsageDescription"]) { + [self.locationManager requestAlwaysAuthorization]; + } else { + NSLog(@"[Warning] No NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription key is defined in the Info.plist file."); + } + return; + } +#endif + + // Tell the location manager to start notifying us of location updates. We + // first stop, and then start the updating to ensure we get at least one + // update, even if our location did not change. + [self.locationManager stopUpdatingLocation]; + [self.locationManager startUpdatingLocation]; + __locationStarted = YES; + if (enableHighAccuracy) { + __highAccuracyEnabled = YES; + // Set distance filter to 5 for a high accuracy. Setting it to "kCLDistanceFilterNone" could provide a + // higher accuracy, but it's also just spamming the callback with useless reports which drain the battery. + self.locationManager.distanceFilter = 5; + // Set desired accuracy to Best. + self.locationManager.desiredAccuracy = kCLLocationAccuracyBest; + } else { + __highAccuracyEnabled = NO; + self.locationManager.distanceFilter = 10; + self.locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers; + } +} + +- (void)_stopLocation +{ + if (__locationStarted) { + if (![self isLocationServicesEnabled]) { + return; + } + + [self.locationManager stopUpdatingLocation]; + __locationStarted = NO; + __highAccuracyEnabled = NO; + } +} + +- (void)locationManager:(CLLocationManager*)manager + didUpdateToLocation:(CLLocation*)newLocation + fromLocation:(CLLocation*)oldLocation +{ + CDVLocationData* cData = self.locationData; + + cData.locationInfo = newLocation; + if (self.locationData.locationCallbacks.count > 0) { + for (NSString* callbackId in self.locationData.locationCallbacks) { + [self returnLocationInfo:callbackId andKeepCallback:NO]; + } + + [self.locationData.locationCallbacks removeAllObjects]; + } + if (self.locationData.watchCallbacks.count > 0) { + for (NSString* timerId in self.locationData.watchCallbacks) { + [self returnLocationInfo:[self.locationData.watchCallbacks objectForKey:timerId] andKeepCallback:YES]; + } + } else { + // No callbacks waiting on us anymore, turn off listening. + [self _stopLocation]; + } +} + +- (void)getLocation:(CDVInvokedUrlCommand*)command +{ + [self.commandDelegate runInBackground:^{ + NSString* callbackId = command.callbackId; + BOOL enableHighAccuracy = [[command argumentAtIndex:0] boolValue]; + + if ([self isLocationServicesEnabled] == NO) { + NSMutableDictionary* posError = [NSMutableDictionary dictionaryWithCapacity:2]; + [posError setObject:[NSNumber numberWithInt:PERMISSIONDENIED] forKey:@"code"]; + [posError setObject:@"Location services are disabled." forKey:@"message"]; + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:posError]; + [self.commandDelegate sendPluginResult:result callbackId:callbackId]; + } else { + if (!self.locationData) { + self.locationData = [[CDVLocationData alloc] init]; + } + CDVLocationData* lData = self.locationData; + if (!lData.locationCallbacks) { + lData.locationCallbacks = [NSMutableArray arrayWithCapacity:1]; + } + + if (!__locationStarted || (__highAccuracyEnabled != enableHighAccuracy)) { + // add the callbackId into the array so we can call back when get data + if (callbackId != nil) { + [lData.locationCallbacks addObject:callbackId]; + } + // Tell the location manager to start notifying us of heading updates + [self startLocation:enableHighAccuracy]; + } else { + [self returnLocationInfo:callbackId andKeepCallback:NO]; + } + } + }]; +} + +- (void)addWatch:(CDVInvokedUrlCommand*)command +{ + NSString* callbackId = command.callbackId; + NSString* timerId = [command argumentAtIndex:0]; + BOOL enableHighAccuracy = [[command argumentAtIndex:1] boolValue]; + + if (!self.locationData) { + self.locationData = [[CDVLocationData alloc] init]; + } + CDVLocationData* lData = self.locationData; + + if (!lData.watchCallbacks) { + lData.watchCallbacks = [NSMutableDictionary dictionaryWithCapacity:1]; + } + + // add the callbackId into the dictionary so we can call back whenever get data + [lData.watchCallbacks setObject:callbackId forKey:timerId]; + + if ([self isLocationServicesEnabled] == NO) { + NSMutableDictionary* posError = [NSMutableDictionary dictionaryWithCapacity:2]; + [posError setObject:[NSNumber numberWithInt:PERMISSIONDENIED] forKey:@"code"]; + [posError setObject:@"Location services are disabled." forKey:@"message"]; + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:posError]; + [self.commandDelegate sendPluginResult:result callbackId:callbackId]; + } else { + if (!__locationStarted || (__highAccuracyEnabled != enableHighAccuracy)) { + // Tell the location manager to start notifying us of location updates + [self startLocation:enableHighAccuracy]; + } + } +} + +- (void)clearWatch:(CDVInvokedUrlCommand*)command +{ + NSString* timerId = [command argumentAtIndex:0]; + + if (self.locationData && self.locationData.watchCallbacks && [self.locationData.watchCallbacks objectForKey:timerId]) { + [self.locationData.watchCallbacks removeObjectForKey:timerId]; + if([self.locationData.watchCallbacks count] == 0) { + [self _stopLocation]; + } + } +} + +- (void)stopLocation:(CDVInvokedUrlCommand*)command +{ + [self _stopLocation]; +} + +- (void)returnLocationInfo:(NSString*)callbackId andKeepCallback:(BOOL)keepCallback +{ + CDVPluginResult* result = nil; + CDVLocationData* lData = self.locationData; + + if (lData && !lData.locationInfo) { + // return error + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageToErrorObject:POSITIONUNAVAILABLE]; + } else if (lData && lData.locationInfo) { + CLLocation* lInfo = lData.locationInfo; + NSMutableDictionary* returnInfo = [NSMutableDictionary dictionaryWithCapacity:8]; + NSNumber* timestamp = [NSNumber numberWithDouble:([lInfo.timestamp timeIntervalSince1970] * 1000)]; + [returnInfo setObject:timestamp forKey:@"timestamp"]; + [returnInfo setObject:[NSNumber numberWithDouble:lInfo.speed] forKey:@"velocity"]; + [returnInfo setObject:[NSNumber numberWithDouble:lInfo.verticalAccuracy] forKey:@"altitudeAccuracy"]; + [returnInfo setObject:[NSNumber numberWithDouble:lInfo.horizontalAccuracy] forKey:@"accuracy"]; + [returnInfo setObject:[NSNumber numberWithDouble:lInfo.course] forKey:@"heading"]; + [returnInfo setObject:[NSNumber numberWithDouble:lInfo.altitude] forKey:@"altitude"]; + [returnInfo setObject:[NSNumber numberWithDouble:lInfo.coordinate.latitude] forKey:@"latitude"]; + [returnInfo setObject:[NSNumber numberWithDouble:lInfo.coordinate.longitude] forKey:@"longitude"]; + + result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:returnInfo]; + [result setKeepCallbackAsBool:keepCallback]; + } + if (result) { + [self.commandDelegate sendPluginResult:result callbackId:callbackId]; + } +} + +- (void)returnLocationError:(NSUInteger)errorCode withMessage:(NSString*)message +{ + NSMutableDictionary* posError = [NSMutableDictionary dictionaryWithCapacity:2]; + + [posError setObject:[NSNumber numberWithUnsignedInteger:errorCode] forKey:@"code"]; + [posError setObject:message ? message:@"" forKey:@"message"]; + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:posError]; + + for (NSString* callbackId in self.locationData.locationCallbacks) { + [self.commandDelegate sendPluginResult:result callbackId:callbackId]; + } + + [self.locationData.locationCallbacks removeAllObjects]; + + for (NSString* callbackId in self.locationData.watchCallbacks) { + [self.commandDelegate sendPluginResult:result callbackId:callbackId]; + } +} + +- (void)locationManager:(CLLocationManager*)manager didFailWithError:(NSError*)error +{ + NSLog(@"locationManager::didFailWithError %@", [error localizedFailureReason]); + + CDVLocationData* lData = self.locationData; + if (lData && __locationStarted) { + // TODO: probably have to once over the various error codes and return one of: + // PositionError.PERMISSION_DENIED = 1; + // PositionError.POSITION_UNAVAILABLE = 2; + // PositionError.TIMEOUT = 3; + NSUInteger positionError = POSITIONUNAVAILABLE; + if (error.code == kCLErrorDenied) { + positionError = PERMISSIONDENIED; + } + [self returnLocationError:positionError withMessage:[error localizedDescription]]; + } + + if (error.code != kCLErrorLocationUnknown) { + [self.locationManager stopUpdatingLocation]; + __locationStarted = NO; + } +} + +//iOS8+ +-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status +{ + if(!__locationStarted){ + [self startLocation:__highAccuracyEnabled]; + } +} + +- (void)dealloc +{ + self.locationManager.delegate = nil; +} + +- (void)onReset +{ + [self _stopLocation]; + [self.locationManager stopUpdatingHeading]; +} + +@end diff --git a/plugins/cordova-plugin-geolocation/src/ubuntu/geolocation.cpp b/plugins/cordova-plugin-geolocation/src/ubuntu/geolocation.cpp new file mode 100644 index 0000000..3d40ab4 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/src/ubuntu/geolocation.cpp @@ -0,0 +1,133 @@ +/* + * + * Copyright 2013-2016 Canonical Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +#include + +#include "geolocation.h" + +Geolocation::Geolocation(Cordova *cordova) + : CPlugin(cordova), + _geoPositionInfoSource(QGeoPositionInfoSource::createDefaultSource(this)) { + if (_geoPositionInfoSource.data() != 0) { + QObject::connect(_geoPositionInfoSource.data(), + SIGNAL(positionUpdated(QGeoPositionInfo)), + this, + SLOT(positionUpdated(QGeoPositionInfo))); + + QObject::connect(_geoPositionInfoSource.data(), + SIGNAL(updateTimeout()), + this, + SLOT(updateTimeout())); + } +} + +void Geolocation::addWatch(int scId, int ecId, const QString &id, bool enableHighAccuracy) { + Q_UNUSED(enableHighAccuracy); + + assert(_id2sc.find(id) == _id2sc.end()); + + if (!_geoPositionInfoSource.data()) { + QVariantMap err; + err.insert("code", POSITION_UNAVAILABLE); + err.insert("message", "unavailable"); + + this->cb(ecId, err); + return; + } + + _id2sc[id] = scId; + _id2ec[id] = ecId; +} + +void Geolocation::clearWatch(int scId, int ecId, const QString &id) { + _id2sc.remove(id); + _id2ec.remove(id); +} + +void Geolocation::getLocation(int scId, int ecId, bool enableHighAccuracy, qint64 maximumAge) { + Q_UNUSED(maximumAge); + Q_UNUSED(enableHighAccuracy); + + if (!_geoPositionInfoSource.data()) { + QVariantMap err; + err.insert("code", POSITION_UNAVAILABLE); + err.insert("message", "unavailable"); + + this->cb(ecId, err); + return; + } + + _geoPositionInfoSource->requestUpdate(); + + QString id = QString("_INTERNAL_") + QUuid::createUuid().toString(); + + _id2sc[id] = scId; + _id2ec[id] = ecId; + _singleUpdate.insert(id); +} + +void Geolocation::positionUpdated(const QGeoPositionInfo &update) { + QGeoCoordinate coordinate = update.coordinate(); + + QVariantMap p; + + p.insert("latitude", coordinate.latitude()); + p.insert("longitude", coordinate.longitude()); + + if (coordinate.type() == QGeoCoordinate::Coordinate3D) + p.insert("altitude", coordinate.altitude()); + + if (update.hasAttribute(QGeoPositionInfo::HorizontalAccuracy)) + p.insert("accuracy", update.attribute(QGeoPositionInfo::HorizontalAccuracy)); + + if (update.hasAttribute(QGeoPositionInfo::Direction)) + p.insert("heading", update.attribute(QGeoPositionInfo::Direction)); + + if (update.hasAttribute(QGeoPositionInfo::GroundSpeed)) + p.insert("velocity", update.attribute(QGeoPositionInfo::GroundSpeed)); + + if (update.hasAttribute(QGeoPositionInfo::VerticalAccuracy)) + p.insert("altitudeAccuracy", update.attribute(QGeoPositionInfo::VerticalAccuracy)); + + p.insert("timestamp", update.timestamp().toMSecsSinceEpoch()); + + for (const QString &id: _id2sc.keys()) { + int scId = _id2sc[id]; + this->cb(scId, p); + if (_singleUpdate.contains(id)) { + _singleUpdate.remove(id); + _id2sc.remove(id); + _id2ec.remove(id); + } + } +} + +void Geolocation::updateTimeout() { + QVariantMap err; + err.insert("code", TIMEOUT); + err.insert("message", "timeout"); + + for (int ecId: _id2ec) { + this->cb(ecId, err); + } + + _id2ec.clear(); + _id2sc.clear(); + _singleUpdate.clear(); +} diff --git a/plugins/cordova-plugin-geolocation/src/ubuntu/geolocation.h b/plugins/cordova-plugin-geolocation/src/ubuntu/geolocation.h new file mode 100644 index 0000000..7345bec --- /dev/null +++ b/plugins/cordova-plugin-geolocation/src/ubuntu/geolocation.h @@ -0,0 +1,69 @@ +/* + * + * Copyright 2013 Canonical Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +#ifndef GEOLOCATION_H_SVO2013 +#define GEOLOCATION_H_SVO2013 + +#include +#include +#include +#include + +#include + +class Geolocation: public CPlugin { + Q_OBJECT +public: + explicit Geolocation(Cordova *cordova); + + virtual const QString fullName() override { + return Geolocation::fullID(); + } + + virtual const QString shortName() override { + return "Geolocation"; + } + + static const QString fullID() { + return "Geolocation"; + } + +public slots: + void getLocation(int scId, int ecId, bool enableHighAccuracy, qint64 maximumAge); + void addWatch(int scId, int ecId, const QString &id, bool enableHighAccuracy); + void clearWatch(int scId, int ecId, const QString &id); + +protected slots: + void positionUpdated(const QGeoPositionInfo &update); + void updateTimeout(); + +private: + QMap _id2sc; + QMap _id2ec; + QSet _singleUpdate; + QSharedPointer _geoPositionInfoSource; + + enum PositionError { + PERMISSION_DENIED = 1, + POSITION_UNAVAILABLE = 2, + TIMEOUT = 3 + }; +}; + +#endif diff --git a/plugins/cordova-plugin-geolocation/src/windows/GeolocationProxy.js b/plugins/cordova-plugin-geolocation/src/windows/GeolocationProxy.js new file mode 100644 index 0000000..03ed495 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/src/windows/GeolocationProxy.js @@ -0,0 +1,202 @@ +/* + * Copyright 2013 Research In Motion Limited. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* global Windows, WinJS */ + +var PositionError = require('./PositionError'); +var callbacks = {}; +var locs = {}; + +// constants +var FALLBACK_EPSILON = 0.001; + +function ensureAndCreateLocator() { + var deferral; + + var loc = new Windows.Devices.Geolocation.Geolocator(); + + if (typeof Windows.Devices.Geolocation.Geolocator.requestAccessAsync === 'function') { + deferral = Windows.Devices.Geolocation.Geolocator.requestAccessAsync().then(function (result) { + if (result === Windows.Devices.Geolocation.GeolocationAccessStatus.allowed) { + return loc; + } + + return WinJS.Promise.wrapError({ + code: PositionError.PERMISSION_DENIED, + message: 'Geolocation access has not been allowed by user.' + }); + }); + } else { + deferral = WinJS.Promise.wrap(loc); + } + + return deferral; +} + +function createErrorCode(loc) { + switch (loc.locationStatus) { + case Windows.Devices.Geolocation.PositionStatus.initializing: + // This status indicates that a location device is still initializing + case Windows.Devices.Geolocation.PositionStatus.noData: + // No location data is currently available + case Windows.Devices.Geolocation.PositionStatus.notInitialized: + // This status indicates that the app has not yet requested + // location data by calling GetGeolocationAsync() or + // registering an event handler for the positionChanged event. + case Windows.Devices.Geolocation.PositionStatus.notAvailable: + // Location is not available on this version of Windows + return PositionError.POSITION_UNAVAILABLE; + + case Windows.Devices.Geolocation.PositionStatus.disabled: + // The app doesn't have permission to access location, + // either because location has been turned off. + return PositionError.PERMISSION_DENIED; + + default: + break; + } +} +function createResult(pos) { + var res = { + accuracy: pos.coordinate.accuracy, + heading: pos.coordinate.heading, + velocity: pos.coordinate.speed, + altitudeAccuracy: pos.coordinate.altitudeAccuracy, + timestamp: pos.coordinate.timestamp + }; + + if (pos.coordinate.point) { + res.latitude = pos.coordinate.point.position.latitude; + res.longitude = pos.coordinate.point.position.longitude; + res.altitude = pos.coordinate.point.position.altitude; + } else { // compatibility with old windows8.0 api + res.latitude = pos.coordinate.latitude; + res.longitude = pos.coordinate.longitude; + res.altitude = pos.coordinate.altitude; + } + + return res; +} + +module.exports = { + getLocation: function (success, fail, args, env) { + ensureAndCreateLocator().done(function (loc) { + if (loc) { + var highAccuracy = args[0], + maxAge = args[1]; + + loc.desiredAccuracy = highAccuracy ? + Windows.Devices.Geolocation.PositionAccuracy.high : + Windows.Devices.Geolocation.PositionAccuracy.default; + + loc.reportInterval = maxAge ? maxAge : 0; + + loc.getGeopositionAsync().then( + function (pos) { + success(createResult(pos)); + }, + function (err) { + fail({ + code: createErrorCode(loc), + message: err.message + }); + } + ); + } + else { + fail({ + code: PositionError.POSITION_UNAVAILABLE, + message: "You do not have the required location services present on your system." + }); + } + }, fail); + }, + + addWatch: function (success, fail, args, env) { + ensureAndCreateLocator().done(function (loc) { + var clientId = args[0]; + var highAccuracy = args[1]; + + var onPositionChanged = function (e) { + success(createResult(e.position), { keepCallback: true }); + }; + + var onStatusChanged = function (e) { + switch (e.status) { + case Windows.Devices.Geolocation.PositionStatus.noData: + case Windows.Devices.Geolocation.PositionStatus.notAvailable: + fail({ + code: PositionError.POSITION_UNAVAILABLE, + message: "Data from location services is currently unavailable or you do not have the required location services present on your system." + }); + break; + + case Windows.Devices.Geolocation.PositionStatus.disabled: + fail({ + code: PositionError.PERMISSION_DENIED, + message: "Your location is currently turned off." + }); + break; + + // case Windows.Devices.Geolocation.PositionStatus.initializing: + // case Windows.Devices.Geolocation.PositionStatus.ready: + default: + break; + } + }; + + loc.desiredAccuracy = highAccuracy ? + Windows.Devices.Geolocation.PositionAccuracy.high : + Windows.Devices.Geolocation.PositionAccuracy.default; + + if (cordova.platformId == 'windows') { + // 'positionchanged' event fails with error below if movementThreshold is not set + // JavaScript runtime error: Operation aborted + // You must set the MovementThreshold property or the ReportInterval property before adding event handlers. + // WinRT information: You must set the MovementThreshold property or the ReportInterval property before adding event handlers + if (Number.EPSILON) { + loc.movementThreshold = Number.EPSILON; + } else { + loc.movementThreshold = FALLBACK_EPSILON; + } + } + + loc.addEventListener("positionchanged", onPositionChanged); + loc.addEventListener("statuschanged", onStatusChanged); + + callbacks[clientId] = { pos: onPositionChanged, status: onStatusChanged }; + locs[clientId] = loc; + }, fail); + }, + + clearWatch: function (success, fail, args, env) { + var clientId = args[0]; + var callback = callbacks[clientId]; + var loc = locs[clientId]; + + if (callback && loc) { + loc.removeEventListener("positionchanged", callback.pos); + loc.removeEventListener("statuschanged", callback.status); + + delete callbacks[clientId]; + delete locs[clientId]; + } + + success(); + } +}; + +require("cordova/exec/proxy").add("Geolocation", module.exports); diff --git a/plugins/cordova-plugin-geolocation/src/wp/GeoLocation.cs b/plugins/cordova-plugin-geolocation/src/wp/GeoLocation.cs new file mode 100644 index 0000000..42af72d --- /dev/null +++ b/plugins/cordova-plugin-geolocation/src/wp/GeoLocation.cs @@ -0,0 +1,34 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; +using System.Threading; +using System.Device.Location; + +namespace WPCordovaClassLib.Cordova.Commands +{ + /// + /// This is a command stub, the browser provides the correct implementation. We use this to trigger the static analyzer that we require this permission + /// + public class Geolocation + { + /* Unreachable code, by design -jm */ + private void triggerGeoInclusion() + { + new GeoCoordinateWatcher(); + } + } +} diff --git a/plugins/cordova-plugin-geolocation/tests/package.json b/plugins/cordova-plugin-geolocation/tests/package.json new file mode 100644 index 0000000..b1e0d86 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/tests/package.json @@ -0,0 +1,14 @@ +{ + "name": "cordova-plugin-geolocation-tests", + "version": "2.4.3-dev", + "description": "", + "cordova": { + "id": "cordova-plugin-geolocation-tests", + "platforms": [] + }, + "keywords": [ + "ecosystem:cordova" + ], + "author": "", + "license": "Apache 2.0" +} diff --git a/plugins/cordova-plugin-geolocation/tests/plugin.xml b/plugins/cordova-plugin-geolocation/tests/plugin.xml new file mode 100644 index 0000000..62d69d2 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/tests/plugin.xml @@ -0,0 +1,32 @@ + + + + + Cordova Geolocation Plugin Tests + Apache 2.0 + + + + + diff --git a/plugins/cordova-plugin-geolocation/tests/tests.js b/plugins/cordova-plugin-geolocation/tests/tests.js new file mode 100644 index 0000000..50c5bfb --- /dev/null +++ b/plugins/cordova-plugin-geolocation/tests/tests.js @@ -0,0 +1,448 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +/* jshint jasmine: true */ +/* global WinJS, device */ + +exports.defineAutoTests = function () { + var fail = function (done, context, message) { + // prevents done() to be called several times + if (context) { + if (context.done) return; + context.done = true; + } + + if (message) { + expect(false).toBe(true, message); + } else { + expect(false).toBe(true); + } + + // watchPosition could call its callback sync (before returning the value) + // so we invoke done async to make sure we know watcher id to .clear in afterEach + setTimeout(function () { + done(); + }); + }; + + var succeed = function (done, context) { + // prevents done() to be called several times + if (context) { + if (context.done) return; + context.done = true; + } + + expect(true).toBe(true); + + // watchPosition could call its callback sync (before returning the value) + // so we invoke done async to make sure we know watcher id to .clear in afterEach + setTimeout(function () { + done(); + }); + }; + + // On Windows, some tests prompt user for permission to use geolocation and interrupt autotests run + var isWindowsStore = (cordova.platformId == "windows8") || (cordova.platformId == "windows" && !WinJS.Utilities.isPhone); + var majorDeviceVersion = null; + var versionRegex = /(\d)\..+/.exec(device.version); + if (versionRegex !== null) { + majorDeviceVersion = Number(versionRegex[1]); + } + // Starting from Android 6.0 there are confirmation dialog which prevents us from running auto tests in silent mode (user interaction needed) + // Also, Android emulator doesn't provide geo fix without manual interactions or mocks + var skipAndroid = cordova.platformId == "android" && (device.isVirtual || majorDeviceVersion >= 6); + var isIOSSim = false; // if iOS simulator does not have a location set, it will fail. + + + describe('Geolocation (navigator.geolocation)', function () { + + it("geolocation.spec.1 should exist", function () { + expect(navigator.geolocation).toBeDefined(); + }); + + it("geolocation.spec.2 should contain a getCurrentPosition function", function () { + expect(typeof navigator.geolocation.getCurrentPosition).toBeDefined(); + expect(typeof navigator.geolocation.getCurrentPosition == 'function').toBe(true); + }); + + it("geolocation.spec.3 should contain a watchPosition function", function () { + expect(typeof navigator.geolocation.watchPosition).toBeDefined(); + expect(typeof navigator.geolocation.watchPosition == 'function').toBe(true); + }); + + it("geolocation.spec.4 should contain a clearWatch function", function () { + expect(typeof navigator.geolocation.clearWatch).toBeDefined(); + expect(typeof navigator.geolocation.clearWatch == 'function').toBe(true); + }); + + }); + + describe('getCurrentPosition method', function () { + + describe('error callback', function () { + + it("geolocation.spec.5 should be called if we set timeout to 0 and maximumAge to a very small number", function (done) { + if (isWindowsStore || skipAndroid) { + pending(); + } + + navigator.geolocation.getCurrentPosition( + fail.bind(null, done), + succeed.bind(null, done), + { + maximumAge: 0, + timeout: 0 + }); + }); + + it("geolocation.spec.9 on failure should return PositionError object with error code constants", function (done) { + if (isWindowsStore || skipAndroid) { + pending(); + } + + navigator.geolocation.getCurrentPosition( + fail.bind(this, done), + function(gpsError) { + // W3C specs: http://dev.w3.org/geo/api/spec-source.html#position_error_interface + expect(gpsError.PERMISSION_DENIED).toBe(1); + expect(gpsError.POSITION_UNAVAILABLE).toBe(2); + expect(gpsError.TIMEOUT).toBe(3); + done(); + }, + { + maximumAge: 0, + timeout: 0 + }); + }); + + }); + + describe('success callback', function () { + + it("geolocation.spec.6 should be called with a Position object", function (done) { + if (isWindowsStore || skipAndroid) { + pending(); + } + + navigator.geolocation.getCurrentPosition(function (p) { + expect(p.coords).toBeDefined(); + expect(p.timestamp).toBeDefined(); + done(); + }, function(err){ + if(err.message && err.message.indexOf('kCLErrorDomain') > -1){ + console.log("Error: Location not set in simulator, tests will fail."); + expect(true).toBe(true); + isIOSSim = true; + done(); + } + else { + fail(done); + } + }, + { + maximumAge: (5 * 60 * 1000) // 5 minutes maximum age of cached position + }); + }, 25000); // first geolocation call can take several seconds on some devices + }); + + }); + + describe('watchPosition method', function () { + + beforeEach(function(done) { + // This timeout is set to lessen the load on platform's geolocation services + // which were causing occasional test failures + setTimeout(function() { + done(); + }, 100); + }); + + describe('error callback', function () { + + var errorWatch = null; + afterEach(function () { + navigator.geolocation.clearWatch(errorWatch); + }); + + it("geolocation.spec.7 should be called if we set timeout to 0 and maximumAge to a very small number", function (done) { + if (isWindowsStore || skipAndroid) { + pending(); + } + + var context = this; + errorWatch = navigator.geolocation.watchPosition( + fail.bind(null, done, context, 'Unexpected win'), + succeed.bind(null, done, context), + { + maximumAge: 0, + timeout: 0 + }); + }); + + it("geolocation.spec.10 on failure should return PositionError object with error code constants", function (done) { + if (isWindowsStore || skipAndroid) { + pending(); + } + + var context = this; + errorWatch = navigator.geolocation.watchPosition( + fail.bind(this, done, context, 'Unexpected win'), + function(gpsError) { + if (context.done) return; + context.done = true; + + // W3C specs: http://dev.w3.org/geo/api/spec-source.html#position_error_interface + expect(gpsError.PERMISSION_DENIED).toBe(1); + expect(gpsError.POSITION_UNAVAILABLE).toBe(2); + expect(gpsError.TIMEOUT).toBe(3); + + done(); + }, + { + maximumAge: 0, + timeout: 0 + }); + }); + + }); + + describe('success callback', function () { + + var successWatch = null; + afterEach(function () { + navigator.geolocation.clearWatch(successWatch); + }); + + it("geolocation.spec.8 should be called with a Position object", function (done) { + if (isWindowsStore || skipAndroid || isIOSSim) { + pending(); + } + + var context = this; + successWatch = navigator.geolocation.watchPosition( + function (p) { + // prevents done() to be called several times + if (context.done) return; + context.done = true; + + expect(p.coords).toBeDefined(); + expect(p.timestamp).toBeDefined(); + // callback could be called sync so we invoke done async to make sure we know watcher id to .clear in afterEach + setTimeout(function () { + done(); + }); + }, + fail.bind(null, done, context, 'Unexpected fail callback'), + { + maximumAge: (5 * 60 * 1000) // 5 minutes maximum age of cached position + }); + expect(successWatch).toBeDefined(); + }); + + }); + + }); + +}; + +/******************************************************************************/ +/******************************************************************************/ +/******************************************************************************/ + +exports.defineManualTests = function (contentEl, createActionButton) { + var watchLocationId = null; + + /** + * Set location status + */ + function setLocationStatus(status) { + document.getElementById('location_status').innerHTML = status; + } + function setLocationDetails(p) { + var date = (new Date(p.timestamp)); + document.getElementById('latitude').innerHTML = p.coords.latitude; + document.getElementById('longitude').innerHTML = p.coords.longitude; + document.getElementById('altitude').innerHTML = p.coords.altitude; + document.getElementById('accuracy').innerHTML = p.coords.accuracy; + document.getElementById('heading').innerHTML = p.coords.heading; + document.getElementById('speed').innerHTML = p.coords.speed; + document.getElementById('altitude_accuracy').innerHTML = p.coords.altitudeAccuracy; + document.getElementById('timestamp').innerHTML = date.toDateString() + " " + date.toTimeString(); + } + + /** + * Stop watching the location + */ + function stopLocation() { + var geo = navigator.geolocation; + if (!geo) { + alert('navigator.geolocation object is missing.'); + return; + } + setLocationStatus("Stopped"); + if (watchLocationId) { + geo.clearWatch(watchLocationId); + watchLocationId = null; + } + } + + /** + * Start watching location + */ + var watchLocation = function () { + var geo = navigator.geolocation; + if (!geo) { + alert('navigator.geolocation object is missing.'); + return; + } + + // Success callback + var success = function (p) { + setLocationDetails(p); + }; + + // Fail callback + var fail = function (e) { + console.log("watchLocation fail callback with error code " + e); + stopLocation(geo); + }; + + // Get location + watchLocationId = geo.watchPosition(success, fail, { enableHighAccuracy: true }); + setLocationStatus("Running"); + }; + + /** + * Get current location + */ + var getLocation = function (opts) { + var geo = navigator.geolocation; + if (!geo) { + alert('navigator.geolocation object is missing.'); + return; + } + + // Stop location if running + stopLocation(geo); + + // Success callback + var success = function (p) { + setLocationDetails(p); + setLocationStatus("Done"); + }; + + // Fail callback + var fail = function (e) { + console.log("getLocation fail callback with error code " + e.code); + setLocationStatus("Error: " + e.code); + }; + + setLocationStatus("Retrieving location..."); + + // Get location + geo.getCurrentPosition(success, fail, opts || { enableHighAccuracy: true }); //, {timeout: 10000}); + + }; + + /******************************************************************************/ + + var location_div = '
' + + 'Status: Stopped' + + '', + latitude = '' + + '' + + '' + + '' + + '', + longitude = '' + + '' + + '' + + '' + + '', + altitude = '' + + '' + + '' + + '' + + '', + accuracy = '' + + '' + + '' + + '' + + '', + heading = '' + + '' + + '' + + '' + + '', + speed = '' + + '' + + '' + + '' + + '', + altitude_accuracy = '' + + '' + + '' + + '' + + '', + time = '' + + '' + + '' + + '' + + '' + + '
Latitude: (decimal degrees) geographic coordinate [#ref]
Longitude: (decimal degrees) geographic coordinate [#ref]
Altitude: null if not supported;
' + + '(meters) height above the [WGS84] ellipsoid. [#ref]
Accuracy: (meters; non-negative; 95% confidence level) the accuracy level of the latitude and longitude coordinates. [#ref]
Heading: null if not supported;
' + + 'NaN if speed == 0;
' + + '(degrees; 0° ≤ heading < 360°) direction of travel of the hosting device- counting clockwise relative to the true north. [#ref]
Speed: null if not supported;
' + + '(meters per second; non-negative) magnitude of the horizontal component of the hosting device current velocity. [#ref]
Altitude Accuracy: null if not supported;
(meters; non-negative; 95% confidence level) the accuracy level of the altitude. [#ref]
Time: (DOMTimeStamp) when the position was acquired [#ref]
' + + '
', + actions = + '
' + + 'Expected result: Will update all applicable values in status box for current location. Status will read Retrieving Location (may not see this if location is retrieved immediately) then Done.' + + '

' + + 'Expected result: Will update all applicable values in status box for current location and update as location changes. Status will read Running.' + + '

' + + 'Expected result: Will stop watching the location so values will not be updated. Status will read Stopped.' + + '

' + + 'Expected result: Will update location values with a cached position that is up to 30 seconds old. Verify with time value. Status will read Done.', + values_info = + '

Details about each value are listed below in the status box

', + note = + '

Allow use of current location, if prompted

'; + + contentEl.innerHTML = values_info + location_div + latitude + longitude + altitude + accuracy + heading + speed + + altitude_accuracy + time + note + actions; + + createActionButton('Get Location', function () { + getLocation(); + }, 'cordova-getLocation'); + + createActionButton('Start Watching Location', function () { + watchLocation(); + }, 'cordova-watchLocation'); + + createActionButton('Stop Watching Location', function () { + stopLocation(); + }, 'cordova-stopLocation'); + + createActionButton('Get Location Up to 30 Sec Old', function () { + getLocation({ maximumAge: 30000 }); + }, 'cordova-getOld'); +}; diff --git a/plugins/cordova-plugin-geolocation/www/Coordinates.js b/plugins/cordova-plugin-geolocation/www/Coordinates.js new file mode 100644 index 0000000..84fdd5b --- /dev/null +++ b/plugins/cordova-plugin-geolocation/www/Coordinates.js @@ -0,0 +1,69 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +/** + * This class contains position information. + * @param {Object} lat + * @param {Object} lng + * @param {Object} alt + * @param {Object} acc + * @param {Object} head + * @param {Object} vel + * @param {Object} altacc + * @constructor + */ +var Coordinates = function(lat, lng, alt, acc, head, vel, altacc) { + /** + * The latitude of the position. + */ + this.latitude = lat; + /** + * The longitude of the position, + */ + this.longitude = lng; + /** + * The accuracy of the position. + */ + this.accuracy = acc; + /** + * The altitude of the position. + */ + this.altitude = (alt !== undefined ? alt : null); + /** + * The direction the device is moving at the position. + */ + this.heading = (head !== undefined ? head : null); + /** + * The velocity with which the device is moving at the position. + */ + this.speed = (vel !== undefined ? vel : null); + + if (this.speed === 0 || this.speed === null) { + this.heading = NaN; + } + + /** + * The altitude accuracy of the position. + */ + this.altitudeAccuracy = (altacc !== undefined) ? altacc : null; +}; + +module.exports = Coordinates; diff --git a/plugins/cordova-plugin-geolocation/www/Position.js b/plugins/cordova-plugin-geolocation/www/Position.js new file mode 100644 index 0000000..d6b2c0c --- /dev/null +++ b/plugins/cordova-plugin-geolocation/www/Position.js @@ -0,0 +1,33 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +var Coordinates = require('./Coordinates'); + +var Position = function(coords, timestamp) { + if (coords) { + this.coords = new Coordinates(coords.latitude, coords.longitude, coords.altitude, coords.accuracy, coords.heading, coords.velocity, coords.altitudeAccuracy); + } else { + this.coords = new Coordinates(); + } + this.timestamp = (timestamp !== undefined) ? timestamp : new Date().getTime(); +}; + +module.exports = Position; diff --git a/plugins/cordova-plugin-geolocation/www/PositionError.js b/plugins/cordova-plugin-geolocation/www/PositionError.js new file mode 100644 index 0000000..9456240 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/www/PositionError.js @@ -0,0 +1,38 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +/** + * Position error object + * + * @constructor + * @param code + * @param message + */ +var PositionError = function(code, message) { + this.code = code || null; + this.message = message || ''; +}; + +PositionError.prototype.PERMISSION_DENIED = PositionError.PERMISSION_DENIED = 1; +PositionError.prototype.POSITION_UNAVAILABLE = PositionError.POSITION_UNAVAILABLE = 2; +PositionError.prototype.TIMEOUT = PositionError.TIMEOUT = 3; + +module.exports = PositionError; diff --git a/plugins/cordova-plugin-geolocation/www/android/geolocation.js b/plugins/cordova-plugin-geolocation/www/android/geolocation.js new file mode 100644 index 0000000..7265bec --- /dev/null +++ b/plugins/cordova-plugin-geolocation/www/android/geolocation.js @@ -0,0 +1,71 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +var exec = cordova.require('cordova/exec'); +var utils = require('cordova/utils'); +var PositionError = require('./PositionError'); + +// Native watchPosition method is called async after permissions prompt. +// So we use additional map and own ids to return watch id synchronously. +var pluginToNativeWatchMap = {}; + +module.exports = { + getCurrentPosition: function(success, error, args) { + var win = function() { + var geo = cordova.require('cordova/modulemapper').getOriginalSymbol(window, 'navigator.geolocation'); + geo.getCurrentPosition(success, error, args); + }; + var fail = function() { + if (error) { + error(new PositionError (PositionError.PERMISSION_DENIED, 'Illegal Access')); + } + }; + exec(win, fail, "Geolocation", "getPermission", []); + }, + + watchPosition: function(success, error, args) { + var pluginWatchId = utils.createUUID(); + + var win = function() { + var geo = cordova.require('cordova/modulemapper').getOriginalSymbol(window, 'navigator.geolocation'); + pluginToNativeWatchMap[pluginWatchId] = geo.watchPosition(success, error, args); + }; + + var fail = function() { + if (error) { + error(new PositionError(PositionError.PERMISSION_DENIED, 'Illegal Access')); + } + }; + exec(win, fail, "Geolocation", "getPermission", []); + + return pluginWatchId; + }, + + clearWatch: function(pluginWatchId) { + var win = function() { + var nativeWatchId = pluginToNativeWatchMap[pluginWatchId]; + var geo = cordova.require('cordova/modulemapper').getOriginalSymbol(window, 'navigator.geolocation'); + geo.clearWatch(nativeWatchId); + }; + + exec(win, null, "Geolocation", "getPermission", []); + } +}; diff --git a/plugins/cordova-plugin-geolocation/www/blackberry10/GeolocationProxy.js b/plugins/cordova-plugin-geolocation/www/blackberry10/GeolocationProxy.js new file mode 100644 index 0000000..0bba226 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/www/blackberry10/GeolocationProxy.js @@ -0,0 +1,69 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +var idsMap = {}, + geo = cordova.require('cordova/modulemapper').getOriginalSymbol(window, 'navigator.geolocation'); + +module.exports = { + + getLocation: function(success, error, args) { + var successCallback = function (result) { + var pos = result.coords; + pos.timestamp = result.timestamp; + if (success) { + success(pos); + } + }; + geo.getCurrentPosition(successCallback, error, { + enableHighAccuracy: args[0], + maximumAge: args[1] + }); + }, + + addWatch: function(success, error, args) { + var id = args[0], + successCallback = function (result) { + var pos = result.coords; + pos.timestamp = result.timestamp; + if (success) { + success(pos); + } + }, + nativeId = geo.watchPosition(successCallback, error, { + enableHighAccuracy: args[1] + }); + idsMap[id] = nativeId; + }, + + clearWatch: function(success, error, args) { + var id = args[0]; + if(id in idsMap) { + geo.clearWatch(idsMap[id]); + delete idsMap[id]; + } + if(success) { + success(); + } + } + +}; + +require("cordova/exec/proxy").add("Geolocation", module.exports); diff --git a/plugins/cordova-plugin-geolocation/www/geolocation.js b/plugins/cordova-plugin-geolocation/www/geolocation.js new file mode 100644 index 0000000..f1f6445 --- /dev/null +++ b/plugins/cordova-plugin-geolocation/www/geolocation.js @@ -0,0 +1,211 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +var argscheck = require('cordova/argscheck'), + utils = require('cordova/utils'), + exec = require('cordova/exec'), + PositionError = require('./PositionError'), + Position = require('./Position'); + +var timers = {}; // list of timers in use + +// Returns default params, overrides if provided with values +function parseParameters(options) { + var opt = { + maximumAge: 0, + enableHighAccuracy: false, + timeout: Infinity + }; + + if (options) { + if (options.maximumAge !== undefined && !isNaN(options.maximumAge) && options.maximumAge > 0) { + opt.maximumAge = options.maximumAge; + } + if (options.enableHighAccuracy !== undefined) { + opt.enableHighAccuracy = options.enableHighAccuracy; + } + if (options.timeout !== undefined && !isNaN(options.timeout)) { + if (options.timeout < 0) { + opt.timeout = 0; + } else { + opt.timeout = options.timeout; + } + } + } + + return opt; +} + +// Returns a timeout failure, closed over a specified timeout value and error callback. +function createTimeout(errorCallback, timeout) { + var t = setTimeout(function() { + clearTimeout(t); + t = null; + errorCallback({ + code:PositionError.TIMEOUT, + message:"Position retrieval timed out." + }); + }, timeout); + return t; +} + +var geolocation = { + lastPosition:null, // reference to last known (cached) position returned + /** + * Asynchronously acquires the current position. + * + * @param {Function} successCallback The function to call when the position data is available + * @param {Function} errorCallback The function to call when there is an error getting the heading position. (OPTIONAL) + * @param {PositionOptions} options The options for getting the position data. (OPTIONAL) + */ + getCurrentPosition:function(successCallback, errorCallback, options) { + argscheck.checkArgs('fFO', 'geolocation.getCurrentPosition', arguments); + options = parseParameters(options); + + // Timer var that will fire an error callback if no position is retrieved from native + // before the "timeout" param provided expires + var timeoutTimer = {timer:null}; + + var win = function(p) { + clearTimeout(timeoutTimer.timer); + if (!(timeoutTimer.timer)) { + // Timeout already happened, or native fired error callback for + // this geo request. + // Don't continue with success callback. + return; + } + var pos = new Position( + { + latitude:p.latitude, + longitude:p.longitude, + altitude:p.altitude, + accuracy:p.accuracy, + heading:p.heading, + velocity:p.velocity, + altitudeAccuracy:p.altitudeAccuracy + }, + p.timestamp + ); + geolocation.lastPosition = pos; + successCallback(pos); + }; + var fail = function(e) { + clearTimeout(timeoutTimer.timer); + timeoutTimer.timer = null; + var err = new PositionError(e.code, e.message); + if (errorCallback) { + errorCallback(err); + } + }; + + // Check our cached position, if its timestamp difference with current time is less than the maximumAge, then just + // fire the success callback with the cached position. + if (geolocation.lastPosition && options.maximumAge && (((new Date()).getTime() - geolocation.lastPosition.timestamp) <= options.maximumAge)) { + successCallback(geolocation.lastPosition); + // If the cached position check failed and the timeout was set to 0, error out with a TIMEOUT error object. + } else if (options.timeout === 0) { + fail({ + code:PositionError.TIMEOUT, + message:"timeout value in PositionOptions set to 0 and no cached Position object available, or cached Position object's age exceeds provided PositionOptions' maximumAge parameter." + }); + // Otherwise we have to call into native to retrieve a position. + } else { + if (options.timeout !== Infinity) { + // If the timeout value was not set to Infinity (default), then + // set up a timeout function that will fire the error callback + // if no successful position was retrieved before timeout expired. + timeoutTimer.timer = createTimeout(fail, options.timeout); + } else { + // This is here so the check in the win function doesn't mess stuff up + // may seem weird but this guarantees timeoutTimer is + // always truthy before we call into native + timeoutTimer.timer = true; + } + exec(win, fail, "Geolocation", "getLocation", [options.enableHighAccuracy, options.maximumAge]); + } + return timeoutTimer; + }, + /** + * Asynchronously watches the geolocation for changes to geolocation. When a change occurs, + * the successCallback is called with the new location. + * + * @param {Function} successCallback The function to call each time the location data is available + * @param {Function} errorCallback The function to call when there is an error getting the location data. (OPTIONAL) + * @param {PositionOptions} options The options for getting the location data such as frequency. (OPTIONAL) + * @return String The watch id that must be passed to #clearWatch to stop watching. + */ + watchPosition:function(successCallback, errorCallback, options) { + argscheck.checkArgs('fFO', 'geolocation.getCurrentPosition', arguments); + options = parseParameters(options); + + var id = utils.createUUID(); + + // Tell device to get a position ASAP, and also retrieve a reference to the timeout timer generated in getCurrentPosition + timers[id] = geolocation.getCurrentPosition(successCallback, errorCallback, options); + + var fail = function(e) { + clearTimeout(timers[id].timer); + var err = new PositionError(e.code, e.message); + if (errorCallback) { + errorCallback(err); + } + }; + + var win = function(p) { + clearTimeout(timers[id].timer); + if (options.timeout !== Infinity) { + timers[id].timer = createTimeout(fail, options.timeout); + } + var pos = new Position( + { + latitude:p.latitude, + longitude:p.longitude, + altitude:p.altitude, + accuracy:p.accuracy, + heading:p.heading, + velocity:p.velocity, + altitudeAccuracy:p.altitudeAccuracy + }, + p.timestamp + ); + geolocation.lastPosition = pos; + successCallback(pos); + }; + + exec(win, fail, "Geolocation", "addWatch", [id, options.enableHighAccuracy]); + + return id; + }, + /** + * Clears the specified heading watch. + * + * @param {String} id The ID of the watch returned from #watchPosition + */ + clearWatch:function(id) { + if (id && timers[id] !== undefined) { + clearTimeout(timers[id].timer); + timers[id].timer = false; + exec(null, null, "Geolocation", "clearWatch", [id]); + } + } +}; + +module.exports = geolocation; diff --git a/plugins/cordova-plugin-insomnia/README.md b/plugins/cordova-plugin-insomnia/README.md new file mode 100644 index 0000000..87d1a9a --- /dev/null +++ b/plugins/cordova-plugin-insomnia/README.md @@ -0,0 +1,146 @@ +# Insomnia-PhoneGap-Plugin + +by [Eddy Verbruggen](http://www.x-services.nl) + +1. [Description](https://github.com/EddyVerbruggen/Insomnia-PhoneGap-Plugin#1-description) +2. [Installation](https://github.com/EddyVerbruggen/Insomnia-PhoneGap-Plugin#2-installation) + 2. [Automatically (CLI / Plugman)](https://github.com/EddyVerbruggen/Insomnia-PhoneGap-Plugin#automatically-cli--plugman) + 2. [Manually](https://github.com/EddyVerbruggen/Insomnia-PhoneGap-Plugin#manually) + 2. [PhoneGap Build](https://github.com/EddyVerbruggen/Insomnia-PhoneGap-Plugin#phonegap-build) +3. [Usage](https://github.com/EddyVerbruggen/Insomnia-PhoneGap-Plugin#3-usage) +4. [Credits](https://github.com/EddyVerbruggen/Insomnia-PhoneGap-Plugin#4-credits) +5. [License](https://github.com/EddyVerbruggen/Insomnia-PhoneGap-Plugin#5-license) + +This is for PhoneGap 3.x, [here is the 2.x version](https://github.com/EddyVerbruggen/Insomnia-PhoneGap-Plugin/tree/phonegap-2.x) + +## 1. Description + +Prevent the screen of the mobile device from falling asleep. + +* The device will never fall asleep after calling `keepAwake`. +* After making your app practically a zombie, you can allow it to sleep again by calling `allowSleepAgain`. +* Works on Android, probably every version you'd care about. +* Works on iOS, probably every version you'd care about. +* Works on Windows and WP8. + +## 2. Installation + +### Automatically (CLI / Plugman) +Insomnia is compatible with [Cordova Plugman](https://github.com/apache/cordova-plugman) and ready for the [PhoneGap 2.9.0 CLI](http://docs.phonegap.com/en/2.9.0/guide_cli_index.md.html#The%20Command-line%20Interface_add_features), here's how it works with the CLI: + +``` +$ phonegap local plugin add https://github.com/EddyVerbruggen/Insomnia-PhoneGap-Plugin.git +``` +or +``` +$ cordova plugin add https://github.com/EddyVerbruggen/Insomnia-PhoneGap-Plugin.git +``` +run this command afterwards: +``` +$ cordova prepare +``` + +The javascript bridge is brought in automatically, so no need to reference Insomnia.js from your html. + +You can also get this plugin [from NPM](https://www.npmjs.com/package/cordova-plugin-insomnia). + +### Manually + +1\. Add the following xml to your `config.xml` in the root directory of your `www` folder: +```xml + + + + +``` + +```xml + + + + +``` + +```xml + + + + +``` + +2\. Grab a copy of Insomnia.js, add it to your project and reference it in `index.html`: +```html + +``` + +3\. Download the source files for iOS and/or Android and copy them to your project. + +iOS: Copy `Insomnia.h` and `Insomnia.h` to `platforms/ios//Plugins` + +Android: Copy `Insomnia.java` to `platforms/android/src/nl/xservices/plugins` (create the folders) + +wp8: Copy `Insomnia.cs` to `platforms/wp8/Plugins/nl.x-services.plugins.insomnia` (create the folders) + +### PhoneGap Build + +Insomnia works with PhoneGap build too, look for Insomnia here: https://build.phonegap.com/plugins/ +Just add the following xml to your `config.xml` to always use the latest version of this plugin: +```xml + +``` +or to use this exact version: +```xml + +``` + +The plugin's javascript file is brought in automatically. Make sure though you include a reference to cordova.js in your index.html's head: +```html + +``` + +## 3. Usage +```html + + +``` +An optional successCallback (first argument) will be triggered if the functions succeed. Even calling `keepAwake` twice will fire the successCallback, because the app will respond as expected (being kept awake). + +An optional errorCallback (second argument) will only be triggered if something fatal happened, preventing the plugin to work as expected. + +### Quirks +[In this issue](#29) it was reported that on iOS the app would fall asleep after the Camera has been used, +even if you previously called `keepAwake`. A similar [issue on Android](#30) where the photo library was accessed during app usage. + +So to make sure your app honors `keepAwake` you have to re-run that method after these kinds of 'external UI' thingies give control back to your app. + +## 4. CREDITS ## + +This plugin was enhanced for Plugman / PhoneGap Build by [Eddy Verbruggen](http://www.x-services.nl). + +The Android code was entirely created by the author. + +The iOS code was heavily inspired by [Wolfgang Koller](https://github.com/simplec-dev/powermanagement). + +Many thanks to [Jesse MacFadyen](https://github.com/purplecabbage) for implementing the wp8 and windows versions! + +## 5. License + +[The MIT License (MIT)](http://www.opensource.org/licenses/mit-license.html) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/plugins/cordova-plugin-insomnia/package.json b/plugins/cordova-plugin-insomnia/package.json new file mode 100644 index 0000000..e7c72d7 --- /dev/null +++ b/plugins/cordova-plugin-insomnia/package.json @@ -0,0 +1,106 @@ +{ + "_args": [ + [ + { + "raw": "cordova-plugin-insomnia", + "scope": null, + "escapedName": "cordova-plugin-insomnia", + "name": "cordova-plugin-insomnia", + "rawSpec": "", + "spec": "latest", + "type": "tag" + }, + "D:\\pWork\\yunkong2.vis.cordova\\node_modules" + ] + ], + "_from": "cordova-plugin-insomnia@latest", + "_id": "cordova-plugin-insomnia@4.3.0", + "_inCache": true, + "_location": "/cordova-plugin-insomnia", + "_nodeVersion": "4.2.2", + "_npmOperationalInternal": { + "host": "packages-18-east.internal.npmjs.com", + "tmp": "tmp/cordova-plugin-insomnia-4.3.0.tgz_1485942457945_0.2706606136634946" + }, + "_npmUser": { + "name": "eddyverbruggen", + "email": "eddyverbruggen@gmail.com" + }, + "_npmVersion": "4.0.5", + "_phantomChildren": {}, + "_requested": { + "raw": "cordova-plugin-insomnia", + "scope": null, + "escapedName": "cordova-plugin-insomnia", + "name": "cordova-plugin-insomnia", + "rawSpec": "", + "spec": "latest", + "type": "tag" + }, + "_requiredBy": [ + "#USER" + ], + "_resolved": "https://registry.npmjs.org/cordova-plugin-insomnia/-/cordova-plugin-insomnia-4.3.0.tgz", + "_shasum": "832a33f6d763f0b80273bdf761b35b678c43b957", + "_shrinkwrap": null, + "_spec": "cordova-plugin-insomnia", + "_where": "D:\\pWork\\yunkong2.vis.cordova\\node_modules", + "author": { + "name": "Eddy Verbruggen", + "email": "eddyverbruggen@gmail.com", + "url": "https://github.com/EddyVerbruggen" + }, + "bugs": { + "url": "https://github.com/EddyVerbruggen/Insomnia-PhoneGap-Plugin/issues" + }, + "cordova": { + "id": "cordova-plugin-insomnia", + "platforms": [ + "ios", + "wp8", + "windows", + "android", + "firefoxos" + ] + }, + "dependencies": {}, + "description": "Prevent the screen of the mobile device from falling asleep.", + "devDependencies": {}, + "directories": {}, + "dist": { + "shasum": "832a33f6d763f0b80273bdf761b35b678c43b957", + "tarball": "https://registry.npmjs.org/cordova-plugin-insomnia/-/cordova-plugin-insomnia-4.3.0.tgz" + }, + "engines": [ + { + "name": "cordova", + "version": ">=3.0.0" + } + ], + "gitHead": "8d2c3b01fc0c11d9bc36bc1b5f9a141bd097f908", + "homepage": "https://github.com/EddyVerbruggen/Insomnia-PhoneGap-Plugin#readme", + "keywords": [ + "ecosystem:cordova", + "cordova-ios", + "cordova-wp8", + "cordova-windows", + "cordova-android", + "cordova-firefoxos" + ], + "license": "MIT", + "maintainers": [ + { + "name": "eddyverbruggen", + "email": "eddyverbruggen@gmail.com" + } + ], + "name": "cordova-plugin-insomnia", + "optionalDependencies": {}, + "readme": "ERROR: No README data found!", + "repository": { + "type": "git", + "url": "git+https://github.com/EddyVerbruggen/Insomnia-PhoneGap-Plugin.git" + }, + "scripts": {}, + "version": "4.3.0" +} diff --git a/plugins/cordova-plugin-insomnia/plugin.xml b/plugins/cordova-plugin-insomnia/plugin.xml new file mode 100644 index 0000000..8d006ca --- /dev/null +++ b/plugins/cordova-plugin-insomnia/plugin.xml @@ -0,0 +1,74 @@ + + + + Insomnia (prevent screen sleep) + + + Prevent the screen of the mobile device from falling asleep. + + + MIT + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/cordova-plugin-insomnia/src/android/nl/xservices/plugins/Insomnia.java b/plugins/cordova-plugin-insomnia/src/android/nl/xservices/plugins/Insomnia.java new file mode 100644 index 0000000..602d48c --- /dev/null +++ b/plugins/cordova-plugin-insomnia/src/android/nl/xservices/plugins/Insomnia.java @@ -0,0 +1,47 @@ +package nl.xservices.plugins; + +import android.view.WindowManager; +import org.apache.cordova.CallbackContext; +import org.apache.cordova.CordovaPlugin; +import org.apache.cordova.PluginResult; +import org.json.JSONArray; +import org.json.JSONException; + +public class Insomnia extends CordovaPlugin { + + private static final String ACTION_KEEP_AWAKE = "keepAwake"; + private static final String ACTION_ALLOW_SLEEP_AGAIN = "allowSleepAgain"; + + @Override + public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException { + try { + if (ACTION_KEEP_AWAKE.equals(action)) { + cordova.getActivity().runOnUiThread( + new Runnable() { + public void run() { + cordova.getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); + } + }); + return true; + + } else if (ACTION_ALLOW_SLEEP_AGAIN.equals(action)) { + cordova.getActivity().runOnUiThread( + new Runnable() { + public void run() { + cordova.getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); + } + }); + return true; + + } else { + callbackContext.error("insomnia." + action + " is not a supported function. Did you mean '" + ACTION_KEEP_AWAKE + "'?"); + return false; + } + } catch (Exception e) { + callbackContext.error(e.getMessage()); + return false; + } + } +} \ No newline at end of file diff --git a/plugins/cordova-plugin-insomnia/src/browser/Insomnia.js b/plugins/cordova-plugin-insomnia/src/browser/Insomnia.js new file mode 100644 index 0000000..87fbd43 --- /dev/null +++ b/plugins/cordova-plugin-insomnia/src/browser/Insomnia.js @@ -0,0 +1,10 @@ +function notSupported() { + console.log('Insomnia is not supported on the browser'); +} + +module.exports = { + keepAwake: notSupported, + allowSleepAgain: notSupported +}; + +require('cordova/exec/proxy').add('Insomnia', module.exports); diff --git a/plugins/cordova-plugin-insomnia/src/firefoxos/insomnia.js b/plugins/cordova-plugin-insomnia/src/firefoxos/insomnia.js new file mode 100644 index 0000000..ed4ea3a --- /dev/null +++ b/plugins/cordova-plugin-insomnia/src/firefoxos/insomnia.js @@ -0,0 +1,16 @@ +var lock; + +module.exports = { + keepAwake: function() { + if (navigator.requestWakeLock) { + lock = navigator.requestWakeLock("screen"); + } + }, + allowSleepAgain: function() { + if (lock && typeof lock.unlock === "function") { + lock.unlock(); + } + } +}; + +require("cordova/exec/proxy").add("Insomnia", module.exports); diff --git a/plugins/cordova-plugin-insomnia/src/ios/Insomnia.h b/plugins/cordova-plugin-insomnia/src/ios/Insomnia.h new file mode 100644 index 0000000..c13c07b --- /dev/null +++ b/plugins/cordova-plugin-insomnia/src/ios/Insomnia.h @@ -0,0 +1,9 @@ +#import + +@interface Insomnia :CDVPlugin + +- (void) keepAwake:(CDVInvokedUrlCommand*)command; + +- (void) allowSleepAgain:(CDVInvokedUrlCommand*)command; + +@end diff --git a/plugins/cordova-plugin-insomnia/src/ios/Insomnia.m b/plugins/cordova-plugin-insomnia/src/ios/Insomnia.m new file mode 100644 index 0000000..7eca3b0 --- /dev/null +++ b/plugins/cordova-plugin-insomnia/src/ios/Insomnia.m @@ -0,0 +1,32 @@ +#import "Insomnia.h" +#import + +@implementation Insomnia + +- (void) keepAwake:(CDVInvokedUrlCommand*)command { + NSString *callbackId = command.callbackId; + + // Acquire a reference to the local UIApplication singleton + UIApplication* app = [UIApplication sharedApplication]; + + if (![app isIdleTimerDisabled]) { + [app setIdleTimerDisabled:true]; + } + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + [self.commandDelegate sendPluginResult:result callbackId:callbackId]; +} + +- (void) allowSleepAgain:(CDVInvokedUrlCommand*)command { + NSString *callbackId = command.callbackId; + + // Acquire a reference to the local UIApplication singleton + UIApplication* app = [UIApplication sharedApplication]; + + if([app isIdleTimerDisabled]) { + [app setIdleTimerDisabled:false]; + } + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + [self.commandDelegate sendPluginResult:result callbackId:callbackId]; +} + +@end \ No newline at end of file diff --git a/plugins/cordova-plugin-insomnia/src/windows/InsomniaProxy.js b/plugins/cordova-plugin-insomnia/src/windows/InsomniaProxy.js new file mode 100644 index 0000000..fc9fa37 --- /dev/null +++ b/plugins/cordova-plugin-insomnia/src/windows/InsomniaProxy.js @@ -0,0 +1,48 @@ + +var displayRequest = null; + +var handleAsyncError = function(handler,msg) { + setTimeout(function(){ + handler(msg); + },0); +}; + +module.exports = { + + keepAwake:function(success,error){ + if(!displayRequest) { + try { + displayRequest = new Windows.System.Display.DisplayRequest(); + displayRequest.requestActive(); + setTimeout(function(){ + success(); + },0); + } + catch(err) { + handleAsyncError(error,"Insomnia failed to activate display request : " + err.message); + } + } + else { + handleAsyncError(error,"Insomnia is wide awake!"); + } + }, + allowSleepAgain:function(success,error){ + if(displayRequest) { + try { + displayRequest.requestRelease(); + displayRequest = null; + setTimeout(function(){ + success(); + },0); + } + catch(err) { + handleAsyncError(error,"Insomnia failed to deactivate display request : " + err.message); + } + } + else { + handleAsyncError(error,"Insomnia is already asleep!"); + } + } +}; + +require("cordova/exec/proxy").add("Insomnia", module.exports); \ No newline at end of file diff --git a/plugins/cordova-plugin-insomnia/src/wp8/Insomnia.cs b/plugins/cordova-plugin-insomnia/src/wp8/Insomnia.cs new file mode 100644 index 0000000..8d5a617 --- /dev/null +++ b/plugins/cordova-plugin-insomnia/src/wp8/Insomnia.cs @@ -0,0 +1,19 @@ +using Microsoft.Phone.Shell; + +namespace WPCordovaClassLib.Cordova.Commands +{ + public class Insomnia : BaseCommand + { + public void keepAwake(string options) + { + PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled; + DispatchCommandResult(new PluginResult(PluginResult.Status.OK)); + } + + public void allowSleepAgain(string options) + { + PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Enabled; + DispatchCommandResult(new PluginResult(PluginResult.Status.OK)); + } + } +} diff --git a/plugins/cordova-plugin-insomnia/www/Insomnia.js b/plugins/cordova-plugin-insomnia/www/Insomnia.js new file mode 100644 index 0000000..f04ab86 --- /dev/null +++ b/plugins/cordova-plugin-insomnia/www/Insomnia.js @@ -0,0 +1,21 @@ +function Insomnia() { +} + +Insomnia.prototype.keepAwake = function (successCallback, errorCallback) { + cordova.exec(successCallback, errorCallback, "Insomnia", "keepAwake", []); +}; + +Insomnia.prototype.allowSleepAgain = function (successCallback, errorCallback) { + cordova.exec(successCallback, errorCallback, "Insomnia", "allowSleepAgain", []); +}; + +Insomnia.install = function () { + if (!window.plugins) { + window.plugins = {}; + } + + window.plugins.insomnia = new Insomnia(); + return window.plugins.insomnia; +}; + +cordova.addConstructor(Insomnia.install); \ No newline at end of file diff --git a/plugins/cordova-plugin-network-information/CONTRIBUTING.md b/plugins/cordova-plugin-network-information/CONTRIBUTING.md new file mode 100644 index 0000000..4c8e6a5 --- /dev/null +++ b/plugins/cordova-plugin-network-information/CONTRIBUTING.md @@ -0,0 +1,37 @@ + + +# Contributing to Apache Cordova + +Anyone can contribute to Cordova. And we need your contributions. + +There are multiple ways to contribute: report bugs, improve the docs, and +contribute code. + +For instructions on this, start with the +[contribution overview](http://cordova.apache.org/contribute/). + +The details are explained there, but the important items are: + - Sign and submit an Apache ICLA (Contributor License Agreement). + - Have a Jira issue open that corresponds to your contribution. + - Run the tests so your patch doesn't break existing functionality. + +We look forward to your contributions! diff --git a/plugins/cordova-plugin-network-information/LICENSE b/plugins/cordova-plugin-network-information/LICENSE new file mode 100644 index 0000000..7a4a3ea --- /dev/null +++ b/plugins/cordova-plugin-network-information/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/plugins/cordova-plugin-network-information/NOTICE b/plugins/cordova-plugin-network-information/NOTICE new file mode 100644 index 0000000..fb19cbd --- /dev/null +++ b/plugins/cordova-plugin-network-information/NOTICE @@ -0,0 +1,8 @@ +Apache Cordova +Copyright 2012 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). + +This product includes software developed by Apple Inc. License can be found in the header of the affected files. (src/ios/CDVReachability.h, src/ios/CDVReachability.m) + diff --git a/plugins/cordova-plugin-network-information/README.md b/plugins/cordova-plugin-network-information/README.md new file mode 100644 index 0000000..d112a10 --- /dev/null +++ b/plugins/cordova-plugin-network-information/README.md @@ -0,0 +1,341 @@ +--- +title: Network Information +description: Get information about wireless connectivity. +--- + + +|Android 4.4|Android 5.1|Android 6.0|iOS 9.3|iOS 10.0|Windows 10 Store|Travis CI| +|:-:|:-:|:-:|:-:|:-:|:-:|:-:| +|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-4.4,PLUGIN=cordova-plugin-network-information)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-4.4,PLUGIN=cordova-plugin-network-information/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-5.1,PLUGIN=cordova-plugin-network-information)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-5.1,PLUGIN=cordova-plugin-network-information/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-6.0,PLUGIN=cordova-plugin-network-information)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-6.0,PLUGIN=cordova-plugin-network-information/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=ios-9.3,PLUGIN=cordova-plugin-network-information)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios-9.3,PLUGIN=cordova-plugin-network-information/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=ios-10.0,PLUGIN=cordova-plugin-network-information)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios-10.0,PLUGIN=cordova-plugin-network-information/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-network-information)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-network-information/)|[![Build Status](https://travis-ci.org/apache/cordova-plugin-network-information.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-network-information)| + +# cordova-plugin-network-information + + +This plugin provides an implementation of an old version of the +[Network Information API](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/). +It provides information about the device's cellular and +wifi connection, and whether the device has an internet connection. + +> To get a few ideas how to use the plugin, check out the [sample](#sample) at the bottom of this page or go straight to the [reference](#reference) content. + +Report issues with this plugin on the [Apache Cordova issue tracker][Apache Cordova issue tracker]. + +##Reference + +## Installation + + cordova plugin add cordova-plugin-network-information + +## Supported Platforms + +- Amazon Fire OS +- Android +- BlackBerry 10 +- Browser +- iOS +- Windows Phone 7 and 8 +- Tizen +- Windows +- Firefox OS + +# Connection + +> The `connection` object, exposed via `navigator.connection`, provides information about the device's cellular and wifi connection. + +## Properties + +- connection.type + +## Constants + +- Connection.UNKNOWN +- Connection.ETHERNET +- Connection.WIFI +- Connection.CELL_2G +- Connection.CELL_3G +- Connection.CELL_4G +- Connection.CELL +- Connection.NONE + +## connection.type + +This property offers a fast way to determine the device's network +connection state, and type of connection. + +### Quick Example + +```js +function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); +} + +checkConnection(); +``` + +### API Change + +Until Cordova 2.3.0, the `Connection` object was accessed via +`navigator.network.connection`, after which it was changed to +`navigator.connection` to match the W3C specification. It's still +available at its original location, but is deprecated and will +eventually be removed. + +### iOS Quirks + +- + +The code examples in this section show examples of changing app behavior using the online and offline events and your network connection status. + +To start with, create a new FileEntry object (data.txt) to use for sample data. Call this function from the `deviceready` handler. + +>*Note* This code example requires the File plugin. + +```js +var dataFileEntry; + +function createSomeData() { + + window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, function (fs) { + + console.log('file system open: ' + fs.name); + // Creates a new file or returns an existing file. + fs.root.getFile("data.txt", { create: true, exclusive: false }, function (fileEntry) { + + dataFileEntry = fileEntry; + + }, onErrorCreateFile); + + }, onErrorLoadFs); +} +``` + +Next, add listeners for the online and offline events in the `deviceready` handler. + +```js +document.addEventListener("offline", onOffline, false); +document.addEventListener("online", onOnline, false); +``` + +The app's `onOnline` function handles the online event. In the event handler, check the current network state. In this app, treat any connection type as good except Connection.NONE. If you have a connection, you try to upload a file. + +```js +function onOnline() { + // Handle the online event + var networkState = navigator.connection.type; + + if (networkState !== Connection.NONE) { + if (dataFileEntry) { + tryToUploadFile(); + } + } + display('Connection type: ' + networkState); +} +``` + +When the online event fires in the preceding code, call the app's `tryToUploadFile` function. + +If the FileTransfer object's upload function fails, call the app's `offlineWrite` function to save the current data somewhere. + +>*Note* This example requires the FileTransfer plugin. + +```js +function tryToUploadFile() { + // !! Assumes variable fileURL contains a valid URL to a text file on the device, + var fileURL = getDataFileEntry().toURL(); + + var success = function (r) { + console.log("Response = " + r.response); + display("Uploaded. Response: " + r.response); + } + + var fail = function (error) { + console.log("An error has occurred: Code = " + error.code); + offlineWrite("Failed to upload: some offline data"); + } + + var options = new FileUploadOptions(); + options.fileKey = "file"; + options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1); + options.mimeType = "text/plain"; + + var ft = new FileTransfer(); + // Make sure you add the domain of your server URL to the + // Content-Security-Policy element in index.html. + ft.upload(fileURL, encodeURI(SERVER), success, fail, options); +}; +``` + +Here is the code for the `offlineWrite` function. + +>*Note* This code examples requires the File plugin. + +```js +function offlineWrite(offlineData) { + // Create a FileWriter object for our FileEntry. + dataFileEntry.createWriter(function (fileWriter) { + + fileWriter.onwriteend = function () { + console.log("Successful file write..."); + display(offlineData); + }; + + fileWriter.onerror = function (e) { + console.log("Failed file write: " + e.toString()); + }; + + fileWriter.write(offlineData); + }); +} +``` + +If the offline event occurs, just do something like notify the user (for this example, just log it). + +```js +function onOffline() { + // Handle the offline event + console.log("lost connection"); +} +``` + +[Apache Cordova issue tracker]: https://issues.apache.org/jira/issues/?jql=project%20%3D%20CB%20AND%20status%20in%20%28Open%2C%20%22In%20Progress%22%2C%20Reopened%29%20AND%20resolution%20%3D%20Unresolved%20AND%20component%20%3D%20%22Plugin%20Network%20Information%22%20ORDER%20BY%20priority%20DESC%2C%20summary%20ASC%2C%20updatedDate%20DESC diff --git a/plugins/cordova-plugin-network-information/RELEASENOTES.md b/plugins/cordova-plugin-network-information/RELEASENOTES.md new file mode 100644 index 0000000..a974304 --- /dev/null +++ b/plugins/cordova-plugin-network-information/RELEASENOTES.md @@ -0,0 +1,163 @@ + +# Release Notes + +### 1.3.3 (Apr 27, 2017) +* [CB-12622](https://issues.apache.org/jira/browse/CB-12622) Add **Android 6.0** build badge to `README` +* [CB-12685](https://issues.apache.org/jira/browse/CB-12685) added `package.json` to tests folder + +### 1.3.2 (Feb 28, 2017) +* [CB-12369](https://issues.apache.org/jira/browse/CB-12369) Add plugin typings from `DefinitelyTyped` +* [CB-12363](https://issues.apache.org/jira/browse/CB-12363) Added build badges for **iOS 9.3** and **iOS 10.0** +* [CB-11838](https://issues.apache.org/jira/browse/CB-11838) **iOS:** Unregister callback function at the right timing. +* [CB-12230](https://issues.apache.org/jira/browse/CB-12230) Removed **Windows 8.1** build badges + +### 1.3.1 (Dec 07, 2016) +* [CB-12224](https://issues.apache.org/jira/browse/CB-12224) Updated version and RELEASENOTES.md for release 1.3.1 +* [CB-11230](https://issues.apache.org/jira/browse/CB-11230) [CB-11505](https://issues.apache.org/jira/browse/CB-11505) iOS: Add compatibility with IPv6 +* [CB-11917](https://issues.apache.org/jira/browse/CB-11917) - Remove pull request template checklist item: "iCLA has been submitted…" +* [CB-11832](https://issues.apache.org/jira/browse/CB-11832) Incremented plugin version. + +### 1.3.0 (Sep 08, 2016) +* [CB-11795](https://issues.apache.org/jira/browse/CB-11795) Add 'protective' entry to cordovaDependencies +* [CB-11734](https://issues.apache.org/jira/browse/CB-11734) Network Plugin uses `Android Log class` and not `Cordova LOG class` +* [CB-11300](https://issues.apache.org/jira/browse/CB-11300) (**android**) Recognize `2G`, `3G` and `4G` network connection subtype names +* Update `NetworkManager.java` +* Detection of Ethernet Network Type on **Android** +* fixed two potential memory leaks when doing Analyze on **iOS 9** +* [CB-11384](https://issues.apache.org/jira/browse/CB-11384) **android**: Does not pass sonarqube scan +* Add badges for paramedic builds on Jenkins +* Add pull request template. +* Readme: Add fenced code blocks with langauage hints +* [CB-10996](https://issues.apache.org/jira/browse/CB-10996) Adding front matter to README.md + +### 1.2.1 (Apr 15, 2016) +* [CB-10763](https://issues.apache.org/jira/browse/CB-10763) Remove emoji in `cordova-plugin-network-information` +* [CB-10636](https://issues.apache.org/jira/browse/CB-10636) Add `JSHint` for plugins + +### 1.2.0 (Jan 15, 2016) +* Adding `CoreTelephony` to `plugin.xml` +* Adding notification for `CT radio` information +* Adding `CT radio` information +* [CB-10160](https://issues.apache.org/jira/browse/CB-10160) Fixed the case mismatch issue + +### 1.1.0 (Nov 18, 2015) +* [CB-10035](https://issues.apache.org/jira/browse/CB-10035) Updated `RELEASENOTES` to be newest to oldest +* Fixing contribute link. +* These notifications are objects so their address always evaluates to true. +* Update `NetworkManager.java` +* [CB-9542](https://issues.apache.org/jira/browse/CB-9542) `Browser Proxy` not defined correctly +* Solved `toLowerCase` issue with `Locale.US` + +### 1.0.1 (Jun 17, 2015) +* Adding .ratignore file. +* [CB-9128](https://issues.apache.org/jira/browse/CB-9128) cordova-plugin-network-information documentation translation: cordova-plugin-network-information +* fix npm md issue + +### 1.0.0 (Apr 15, 2015) +* [CB-8746](https://issues.apache.org/jira/browse/CB-8746) gave plugin major version bump +* [CB-8683](https://issues.apache.org/jira/browse/CB-8683) changed plugin-id to pacakge-name +* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) properly updated translated docs to use new id +* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) updated translated docs to use new id +* [CB-8185](https://issues.apache.org/jira/browse/CB-8185) Fixes typo in `cordova.platformId` +* Use TRAVIS_BUILD_DIR, install paramedic by npm +* [CB-8185](https://issues.apache.org/jira/browse/CB-8185) Use `navigator.onLine` as connection information source on browser platform +* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) Updated Readme +* [CB-8659](https://issues.apache.org/jira/browse/CB-8659): ios: 4.0.x Compatibility: Remove use of initWebView method +* [CB-8573](https://issues.apache.org/jira/browse/CB-8573) Integrate TravisCI +* [CB-8438](https://issues.apache.org/jira/browse/CB-8438) cordova-plugin-network-information documentation translation: cordova-plugin-network-information +* [CB-8538](https://issues.apache.org/jira/browse/CB-8538) Added package.json file + +### 0.2.15 (Feb 04, 2015) +* [CB-8384](https://issues.apache.org/jira/browse/CB-8384) Network status change support on Windows +* [CB-8384](https://issues.apache.org/jira/browse/CB-8384) Fixes the way we detect online status on Windows +* [CB-8384](https://issues.apache.org/jira/browse/CB-8384) Add Windows platform quirks +* [CB-8384](https://issues.apache.org/jira/browse/CB-8384) Add Windows section to Network Information plugin + +### 0.2.14 (Dec 02, 2014) +* [CB-7976](https://issues.apache.org/jira/browse/CB-7976) **Android**: Use webView's context rather than Activity's context for intent receiver +* [CB-7700](https://issues.apache.org/jira/browse/CB-7700) cordova-plugin-network-information documentation translation: cordova-plugin-network-information + +### 0.2.13 (Oct 03, 2014) +* [CB-7595](https://issues.apache.org/jira/browse/CB-7595): Android L changes the type from Mobile to Cellular, I'm pretty sure this isn't documented + +### 0.2.12 (Sep 17, 2014) +* [CB-7471](https://issues.apache.org/jira/browse/CB-7471) cordova-plugin-network-information documentation translation +* Fix network information type exception on fxos 2 +* Added support for the browser +* [CB-6724](https://issues.apache.org/jira/browse/CB-6724) added documentation for manual tests +* remove reference to test assets, they are optional +* Renamed test dir and added nested plugin.xml +* [CB-6964](https://issues.apache.org/jira/browse/CB-6964) ported manual tests +* Port network tests to plugin-test-framework +* Fix naviagtor typo + +### 0.2.11 (Aug 06, 2014) +* **FFOS** update NetworkProxy.js +* [CB-6127](https://issues.apache.org/jira/browse/CB-6127) Updated translations for docs +* [CB-7019](https://issues.apache.org/jira/browse/CB-7019) Updated version and RELEASENOTES.md for release 0.2.10 +* Fixed docs for online/offline event being backwards + +### 0.2.10 (Jun 24, 2014) +* [CB-6907](https://issues.apache.org/jira/browse/CB-6907): [android] Don't crash on startup if no networks available + +### 0.2.9 (Jun 05, 2014) +* updated notice file to include missing license +* Cached extra info to better detect changes. +* [CB-6809](https://issues.apache.org/jira/browse/CB-6809) Add license to CONTRIBUTING.md +* [CB-6491](https://issues.apache.org/jira/browse/CB-6491) add CONTRIBUTING.md +* [CB-6350](https://issues.apache.org/jira/browse/CB-6350) - Fix networkStatusForFlags return value type to work with 64-bit iOS (closes #8) +* Initial version of firefox os network information plugin +* there was an error in the object definition + +### 0.2.8 (Apr 17, 2014) +* [CB-6342](https://issues.apache.org/jira/browse/CB-6342): [iOS] iOS reports a cellular connection even when in Airplane mode +* [CB-6422](https://issues.apache.org/jira/browse/CB-6422): [windows8] use cordova/exec/proxy +* [CB-6460](https://issues.apache.org/jira/browse/CB-6460): Update license headers +* [CB-6465](https://issues.apache.org/jira/browse/CB-6465): Add license headers to Tizen code +* Add NOTICE file + +### 0.2.7 (Feb 05, 2014) +* Initial implementation of Tizen plugin. + +### 0.2.6 (Jan 02, 2014) +* [CB-5658](https://issues.apache.org/jira/browse/CB-5658) Add doc/index.md for netinfo plugin + +### 0.2.5 (Dec 4, 2013) +* [ubuntu] specify policy_group +* add ubuntu platform +* Added amazon-fireos platform. Change to use amazon-fireos as the platform if user agent string contains 'cordova-amazon-fireos' + +### 0.2.4 (Oct 28, 2013) +* [CB-5128](https://issues.apache.org/jira/browse/CB-5128): add repo + issue tag to plugin.xml for network information plugin +* [CB-4915](https://issues.apache.org/jira/browse/CB-4915) Incremented plugin version on dev branch. + +### 0.2.3 (Sept 25, 2013) +* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) bumping&resetting version +* [windows8] commandProxy was moved +* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) renaming org.apache.cordova.core.network-information to org.apache.cordova.network-information +* removed duplicate comment line from plugin.xml +* added Network APIs for FirefoxOS +* Rename CHANGELOG.md -> RELEASENOTES.md +* [CB-4752](https://issues.apache.org/jira/browse/CB-4752) Incremented plugin version on dev branch. + +### 0.2.1 (Sept 5, 2013) +* [CB-4432](https://issues.apache.org/jira/browse/CB-4432) copyright notice change diff --git a/plugins/cordova-plugin-network-information/doc/de/README.md b/plugins/cordova-plugin-network-information/doc/de/README.md new file mode 100644 index 0000000..f6292b2 --- /dev/null +++ b/plugins/cordova-plugin-network-information/doc/de/README.md @@ -0,0 +1,190 @@ + + +# cordova-plugin-network-information + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-network-information.svg)](https://travis-ci.org/apache/cordova-plugin-network-information) + +Dieses Plugin stellt eine Implementierung einer alten Version der [Netzwerk-Informationen-API](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/). Es werden Informationen über das Gerät Mobilfunk und Wifi-Anschluss, und ob das Gerät über eine Internetverbindung verfügt. + +## Installation + + cordova plugin add cordova-plugin-network-information + + +## Unterstützte Plattformen + + * Amazon Fire OS + * Android + * BlackBerry 10 + * Browser + * iOS + * Windows Phone 7 und 8 + * Tizen + * Windows + * Firefox OS + +# Connection + +> Das `connection` Objekt, verfügbar gemachten über `navigator.connection`, enthält Informationen über die Mobilfunk- und Wi-Fi-Verbindung des Gerätes. + +## Eigenschaften + + * connection.type + +## Konstanten + + * Connection.UNKNOWN + * Connection.ETHERNET + * Connection.WIFI + * Connection.CELL_2G + * Connection.CELL_3G + * Connection.CELL_4G + * Connection.CELL + * Connection.NONE + +## connection.type + +Diese Eigenschaft bietet eine schnelle Möglichkeit, um den Netzwerkverbindungsstatus und die Art der Verbindung zu bestimmen. + +### Kurzes Beispiel + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### API Änderung + +Bis Cordova 2.3.0 wurde auf das `Connection` Objekt über `navigator.network.connection` zugegriffen, danach wurde der Zugriff auf `navigator.connection` geändert, um der W3C-Spezifikation zu entsprechen. Es steht immer noch an seiner ursprünglichen Stelle, aber ist veraltet und wird schliesslich entfernt. + +### iOS Macken + + * iOS kann Mobilfunknetz Verbindungstyp nicht erkennen. + * `navigator.connection.type`auf festgelegt ist `Connection.CELL` für alle Handy-Daten. + +### Windows Phone Macken + + * Wenn im Emulator ausgeführt wird, erkennt immer `navigator.connection.type` als`Connection.UNKNOWN`. + + * Windows Phone kann Mobilfunknetz Verbindungstyp nicht erkennen. + + * `navigator.connection.type`auf festgelegt ist `Connection.CELL` für alle Handy-Daten. + +### Windows-Eigenheiten + + * Wenn im Telefon 8.1 Emulator ausgeführt wird, erkennt immer `navigator.connection.type` als `Connection.ETHERNET`. + +### Tizen Macken + + * Tizen kann nur ein WiFi oder Mobilfunkverbindung erkennen. + * `Navigator.Connection.Type` ist für alle Handy-Daten auf `Connection.CELL_2G` festgelegt. + +### Firefox OS Macken + + * Firefox-OS kann Mobilfunknetz Verbindungstyp nicht erkennen. + * `navigator.connection.type`auf festgelegt ist `Connection.CELL` für alle Handy-Daten. + +### Browser-Eigenheiten + + * Browser kann die Art der Netzwerkverbindung nicht erkennen. `navigator.connection.type` ist immer auf `Connection.UNKNOWN` beim online gesetzt. + +# Netzwerk-Veranstaltungen + +## offline + +Das Ereignis wird ausgelöst, wenn eine Anwendung offline geht, und das Gerät nicht mit dem Internet verbunden ist. + + document.addEventListener("offline", yourCallbackFunction, false); + + +### Details + +Das `offline` -Ereignis wird ausgelöst, wenn ein bereits angeschlossenes Gerät eine Netzwerkverbindung verliert, so dass eine Anwendung nicht mehr auf das Internet zugreifen kann. Es stützt sich auf die gleichen Informationen wie die Verbindung-API und wird ausgelöst, wenn der Wert des `connection.type` wird`NONE`. + +Anwendungen sollten in der Regel verwenden `document.addEventListener` einmal einen Ereignis-Listener hinzufügen das `deviceready` -Ereignis ausgelöst. + +### Kurzes Beispiel + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### iOS Macken + +Beim ersten Start dauert das erste offline-Event (falls zutreffend) mindestens eine Sekunde zu schießen. + +### Windows Phone 7 Macken + +Bei der Ausführung im Emulator, der `connection.status` ist immer unbekannt, so dass dieses Ereignis *nicht* Feuer. + +### Windows Phone 8 Macken + +Der Emulator meldet den Verbindungstyp als `Cellular` , die wird nicht geändert, so dass das Ereignis *nicht* Feuer. + +## online + +Dieses Ereignis wird ausgelöst, wenn eine Anwendung online geht, und das Gerät wird mit dem Internet verbunden. + + document.addEventListener("online", yourCallbackFunction, false); + + +### Details + +Das `online` -Ereignis wird ausgelöst, wenn ein zuvor unverbundenen Gerät eine Netzwerkverbindung zu einem Anwendung Zugriff auf das Internet empfängt. Es stützt sich auf die gleichen Informationen wie die Verbindung-API und wird ausgelöst, wenn die `connection.type` ändert sich von `NONE` auf einen anderen Wert. + +Anwendungen sollten in der Regel verwenden `document.addEventListener` einmal einen Ereignis-Listener hinzufügen das `deviceready` -Ereignis ausgelöst. + +### Kurzes Beispiel + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### iOS Macken + +Beim ersten Start die erste `online` Ereignis (falls zutreffend) dauert mindestens eine Sekunde vor dem Feuer `connection.type` ist`UNKNOWN`. + +### Windows Phone 7 Macken + +Bei der Ausführung im Emulator, der `connection.status` ist immer unbekannt, so dass dieses Ereignis *nicht* Feuer. + +### Windows Phone 8 Macken + +Der Emulator meldet den Verbindungstyp als `Cellular` , die wird nicht geändert, so dass Ereignisse *nicht* Feuer. \ No newline at end of file diff --git a/plugins/cordova-plugin-network-information/doc/de/index.md b/plugins/cordova-plugin-network-information/doc/de/index.md new file mode 100644 index 0000000..537328a --- /dev/null +++ b/plugins/cordova-plugin-network-information/doc/de/index.md @@ -0,0 +1,186 @@ + + +# cordova-plugin-network-information + +Dieses Plugin stellt eine Implementierung einer alten Version der [Netzwerk-Informationen-API][1]. Es werden Informationen über das Gerät Mobilfunk und Wifi-Anschluss, und ob das Gerät über eine Internetverbindung verfügt. + + [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ + +## Installation + + cordova plugin add cordova-plugin-network-information + + +## Unterstützte Plattformen + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Browser +* iOS +* Windows Phone 7 und 8 +* Tizen +* Windows +* Firefox OS + +# Connection + +> Das `connection` Objekt, verfügbar gemachten über `navigator.connection`, enthält Informationen über die Mobilfunk- und Wi-Fi-Verbindung des Gerätes. + +## Eigenschaften + +* connection.type + +## Konstanten + +* Connection.UNKNOWN +* Connection.ETHERNET +* Connection.WIFI +* Connection.CELL_2G +* Connection.CELL_3G +* Connection.CELL_4G +* Connection.CELL +* Connection.NONE + +## connection.type + +Diese Eigenschaft bietet eine schnelle Möglichkeit, um den Netzwerkverbindungsstatus und die Art der Verbindung zu bestimmen. + +### Kurzes Beispiel + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### API Änderung + +Bis Cordova 2.3.0 wurde auf das `Connection` Objekt über `navigator.network.connection` zugegriffen, danach wurde der Zugriff auf `navigator.connection` geändert, um der W3C-Spezifikation zu entsprechen. Es steht immer noch an seiner ursprünglichen Stelle, aber ist veraltet und wird schliesslich entfernt. + +### iOS Macken + +* iOS kann Mobilfunknetz Verbindungstyp nicht erkennen. + * `navigator.connection.type`auf festgelegt ist `Connection.CELL` für alle Handy-Daten. + +### Windows Phone Macken + +* Wenn im Emulator ausgeführt wird, erkennt immer `navigator.connection.type` als`Connection.UNKNOWN`. + +* Windows Phone kann Mobilfunknetz Verbindungstyp nicht erkennen. + + * `navigator.connection.type`auf festgelegt ist `Connection.CELL` für alle Handy-Daten. + +### Windows-Eigenheiten + +* Wenn im Telefon 8.1 Emulator ausgeführt wird, erkennt immer `navigator.connection.type` als `Connection.ETHERNET`. + +### Tizen Macken + +* Tizen kann nur ein WiFi oder Mobilfunkverbindung erkennen. + * `Navigator.Connection.Type` ist für alle Handy-Daten auf `Connection.CELL_2G` festgelegt. + +### Firefox OS Macken + +* Firefox-OS kann Mobilfunknetz Verbindungstyp nicht erkennen. + * `navigator.connection.type`auf festgelegt ist `Connection.CELL` für alle Handy-Daten. + +# Netzwerk-Veranstaltungen + +## offline + +Das Ereignis wird ausgelöst, wenn eine Anwendung offline geht, und das Gerät nicht mit dem Internet verbunden ist. + + document.addEventListener("offline", yourCallbackFunction, false); + + +### Details + +Das `offline` -Ereignis wird ausgelöst, wenn ein bereits angeschlossenes Gerät eine Netzwerkverbindung verliert, so dass eine Anwendung nicht mehr auf das Internet zugreifen kann. Es stützt sich auf die gleichen Informationen wie die Verbindung-API und wird ausgelöst, wenn der Wert des `connection.type` wird`NONE`. + +Anwendungen sollten in der Regel verwenden `document.addEventListener` einmal einen Ereignis-Listener hinzufügen das `deviceready` -Ereignis ausgelöst. + +### Kurzes Beispiel + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### iOS Macken + +Beim ersten Start dauert das erste offline-Event (falls zutreffend) mindestens eine Sekunde zu schießen. + +### Windows Phone 7 Macken + +Bei der Ausführung im Emulator, der `connection.status` ist immer unbekannt, so dass dieses Ereignis *nicht* Feuer. + +### Windows Phone 8 Macken + +Der Emulator meldet den Verbindungstyp als `Cellular` , die wird nicht geändert, so dass das Ereignis *nicht* Feuer. + +## online + +Dieses Ereignis wird ausgelöst, wenn eine Anwendung online geht, und das Gerät wird mit dem Internet verbunden. + + document.addEventListener("online", yourCallbackFunction, false); + + +### Details + +Das `online` -Ereignis wird ausgelöst, wenn ein zuvor unverbundenen Gerät eine Netzwerkverbindung zu einem Anwendung Zugriff auf das Internet empfängt. Es stützt sich auf die gleichen Informationen wie die Verbindung-API und wird ausgelöst, wenn die `connection.type` ändert sich von `NONE` auf einen anderen Wert. + +Anwendungen sollten in der Regel verwenden `document.addEventListener` einmal einen Ereignis-Listener hinzufügen das `deviceready` -Ereignis ausgelöst. + +### Kurzes Beispiel + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### iOS Macken + +Beim ersten Start die erste `online` Ereignis (falls zutreffend) dauert mindestens eine Sekunde vor dem Feuer `connection.type` ist`UNKNOWN`. + +### Windows Phone 7 Macken + +Bei der Ausführung im Emulator, der `connection.status` ist immer unbekannt, so dass dieses Ereignis *nicht* Feuer. + +### Windows Phone 8 Macken + +Der Emulator meldet den Verbindungstyp als `Cellular` , die wird nicht geändert, so dass Ereignisse *nicht* Feuer. diff --git a/plugins/cordova-plugin-network-information/doc/es/README.md b/plugins/cordova-plugin-network-information/doc/es/README.md new file mode 100644 index 0000000..4e30593 --- /dev/null +++ b/plugins/cordova-plugin-network-information/doc/es/README.md @@ -0,0 +1,190 @@ + + +# cordova-plugin-network-information + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-network-information.svg)](https://travis-ci.org/apache/cordova-plugin-network-information) + +Este plugin proporciona una implementación de una versión antigua de la [Red de información API](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/). Proporciona información acerca del dispositivo móvil y conexión wifi, y si el dispositivo tiene una conexión a internet. + +## Instalación + + cordova plugin add cordova-plugin-network-information + + +## Plataformas soportadas + + * Amazon fire OS + * Android + * BlackBerry 10 + * Explorador + * iOS + * Windows Phone 7 y 8 + * Tizen + * Windows + * Firefox OS + +# Connection + +> El objeto de `connection`, expuesto a través de `navigator.connection`, proporciona información sobre conexión celular y wifi del dispositivo. + +## Propiedades + + * connection.type + +## Constantes + + * Connection.UNKNOWN + * Connection.ETHERNET + * Connection.WIFI + * Connection.CELL_2G + * Connection.CELL_3G + * Connection.CELL_4G + * Connection.CELL + * Connection.NONE + +## connection.type + +Esta propiedad ofrece una forma rápida de determinar el estado de conexión de red del dispositivo y el tipo de conexión. + +### Ejemplo rápido + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### Cambio de API + +Hasta Cordova 2.3.0, el objeto de `conexión` era acceder a través de `navigator.network.connection`, tras lo cual fue cambiada a `navigator.connection` para que coincida con la especificación del W3C. Sigue estando disponible en su ubicación original, pero es obsoleto y eventualmente desaparecerá. + +### iOS rarezas + + * iOS no puede detectar el tipo de conexión de red celular. + * `navigator.connection.type` está establecido en `Connection.CELL` para todos los datos de celulares. + +### Windows Phone rarezas + + * Cuando se ejecuta en el emulador, siempre detecta `navigator.connection.type` como `Connection.UNKNOWN`. + + * Windows Phone no puede detectar el tipo de conexión de red celular. + + * `navigator.connection.type` está establecido en `Connection.CELL` para todos los datos de celulares. + +### Windows rarezas + + * Cuando se ejecuta en el emulador de teléfono 8.1, siempre detecta `navigator.connection.type` como`Connection.ETHERNET`. + +### Rarezas Tizen + + * Tizen sólo puede detectar un Wi-Fi o conexión celular. + * `navigator.connection.type`se establece en `Connection.CELL_2G` para todos los datos celulares. + +### Firefox OS rarezas + + * Firefox OS no puede detectar el tipo de conexión de red celular. + * `navigator.connection.type` está establecido en `Connection.CELL` para todos los datos de celulares. + +### Navegador rarezas + + * Navegador no puede detectar el tipo de conexión de red. `Navigator.Connection.Type` se encuentra siempre a `Connection.UNKNOWN` cuando en línea. + +# Eventos relacionados con la red + +## offline + +El evento se desencadena cuando una aplicación está desconectada, y el dispositivo no está conectado a Internet. + + document.addEventListener("offline", yourCallbackFunction, false); + + +### Detalles + +El evento `offline` se desencadena cuando un dispositivo conectado previamente pierde una conexión de red para que una aplicación no puede acceder a Internet. Se basa en la misma información que la API de conexión y cuando se dispara el valor del `connection.type` se convierte`NONE`. + +Las aplicaciones normalmente deben utilizar `document.addEventListener` para conectar un detector de eventos una vez que se desencadene el evento `deviceready`. + +### Ejemplo rápido + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### iOS rarezas + +Durante el arranque inicial, el primer evento offline (si es aplicable) tarda al menos un segundo en fuego. + +### Windows Phone 7 rarezas + +Cuando se ejecuta en el emulador, la `connection.status` siempre es desconocido, así que este evento no se ** fuego. + +### Windows Phone 8 rarezas + +El emulador informa el tipo de conexión como `celular`, que no cambia, así que el evento *no se* fuego. + +## online + +Este evento se desencadena cuando una aplicación va en línea, y el dispositivo se conecta a Internet. + + document.addEventListener("online", yourCallbackFunction, false); + + +### Detalles + +El evento `online` se desencadena cuando un dispositivo previamente inconexos recibe una conexión de red para permitir un acceso a las aplicaciones para Internet. Se basa en la misma información que la API de conexión y se desencadena cuando el `connection.type` cambia de `ninguno` a cualquier otro valor. + +Las aplicaciones normalmente deben utilizar `document.addEventListener` para conectar un detector de eventos una vez que se desencadene el evento `deviceready`. + +### Ejemplo rápido + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### iOS rarezas + +Durante el arranque inicial, el primer evento `en línea` (si procede) al menos toma un segundo para disparar, antes de que `connection.type` es `desconocido`. + +### Windows Phone 7 rarezas + +Cuando se ejecuta en el emulador, la `connection.status` siempre es desconocido, así que este evento no se ** fuego. + +### Windows Phone 8 rarezas + +El emulador, informa el tipo de conexión como `Cellular` , que no cambia, así que se lo eventos *no* fuego. \ No newline at end of file diff --git a/plugins/cordova-plugin-network-information/doc/es/index.md b/plugins/cordova-plugin-network-information/doc/es/index.md new file mode 100644 index 0000000..65158ef --- /dev/null +++ b/plugins/cordova-plugin-network-information/doc/es/index.md @@ -0,0 +1,186 @@ + + +# cordova-plugin-network-information + +Este plugin proporciona una implementación de una versión antigua de la [Red de información API][1]. Proporciona información acerca del dispositivo móvil y conexión wifi, y si el dispositivo tiene una conexión a internet. + + [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ + +## Instalación + + cordova plugin add cordova-plugin-network-information + + +## Plataformas soportadas + +* Amazon fire OS +* Android +* BlackBerry 10 +* Explorador +* iOS +* Windows Phone 7 y 8 +* Tizen +* Windows +* Firefox OS + +# Conexión + +> El objeto de `connection`, expuesto a través de `navigator.connection`, proporciona información sobre conexión celular y wifi del dispositivo. + +## Propiedades + +* connection.type + +## Constantes + +* Connection.UNKNOWN +* Connection.ETHERNET +* Connection.WIFI +* Connection.CELL_2G +* Connection.CELL_4G +* Connection.CELL_3G +* Connection.CELL +* Connection.NONE + +## connection.type + +Esta propiedad ofrece una forma rápida de determinar el estado de conexión de red del dispositivo y el tipo de conexión. + +### Ejemplo rápido + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### Cambio de API + +Hasta Cordova 2.3.0, el objeto de `conexión` era acceder a través de `navigator.network.connection`, tras lo cual fue cambiada a `navigator.connection` para que coincida con la especificación del W3C. Sigue estando disponible en su ubicación original, pero es obsoleto y eventualmente desaparecerá. + +### iOS rarezas + +* iOS no puede detectar el tipo de conexión de red celular. + * `navigator.connection.type` está establecido en `Connection.CELL` para todos los datos de celulares. + +### Windows Phone rarezas + +* Cuando se ejecuta en el emulador, siempre detecta `navigator.connection.type` como `Connection.UNKNOWN`. + +* Windows Phone no puede detectar el tipo de conexión de red celular. + + * `navigator.connection.type` está establecido en `Connection.CELL` para todos los datos de celulares. + +### Windows rarezas + +* Cuando se ejecuta en el emulador de teléfono 8.1, siempre detecta `navigator.connection.type` como`Connection.ETHERNET`. + +### Rarezas Tizen + +* Tizen sólo puede detectar un Wi-Fi o conexión celular. + * `navigator.connection.type`se establece en `Connection.CELL_2G` para todos los datos celulares. + +### Firefox OS rarezas + +* Firefox OS no puede detectar el tipo de conexión de red celular. + * `navigator.connection.type`se establece en `Connection.CELL` para todos los datos celulares. + +# Eventos relacionados con la red + +## offline + +El evento se desencadena cuando una aplicación está desconectada, y el dispositivo no está conectado a Internet. + + document.addEventListener("offline", yourCallbackFunction, false); + + +### Detalles + +El evento `offline` se desencadena cuando un dispositivo conectado previamente pierde una conexión de red para que una aplicación no puede acceder a Internet. Se basa en la misma información que la API de conexión y cuando se dispara el valor del `connection.type` se convierte`NONE`. + +Las aplicaciones normalmente deben utilizar `document.addEventListener` para conectar un detector de eventos una vez que se desencadene el evento `deviceready`. + +### Ejemplo rápido + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### iOS rarezas + +Durante el arranque inicial, el primer evento offline (si es aplicable) tarda al menos un segundo en fuego. + +### Windows Phone 7 rarezas + +Cuando se ejecuta en el emulador, la `connection.status` siempre es desconocido, así que este evento no se ** fuego. + +### Windows Phone 8 rarezas + +El emulador informa el tipo de conexión como `celular`, que no cambia, así que el evento *no se* fuego. + +## online + +Este evento se desencadena cuando una aplicación va en línea, y el dispositivo se conecta a Internet. + + document.addEventListener("online", yourCallbackFunction, false); + + +### Detalles + +El evento `online` se desencadena cuando un dispositivo previamente inconexos recibe una conexión de red para permitir un acceso a las aplicaciones para Internet. Se basa en la misma información que la API de conexión y se desencadena cuando el `connection.type` cambia de `ninguno` a cualquier otro valor. + +Las aplicaciones normalmente deben utilizar `document.addEventListener` para conectar un detector de eventos una vez que se desencadene el evento `deviceready`. + +### Ejemplo rápido + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### iOS rarezas + +Durante el arranque inicial, el primer evento `en línea` (si procede) al menos toma un segundo para disparar, antes de que `connection.type` es `desconocido`. + +### Windows Phone 7 rarezas + +Cuando se ejecuta en el emulador, la `connection.status` siempre es desconocido, así que este evento no se ** fuego. + +### Windows Phone 8 rarezas + +El emulador, informa el tipo de conexión como `Cellular` , que no cambia, así que se lo eventos *no* fuego. diff --git a/plugins/cordova-plugin-network-information/doc/fr/README.md b/plugins/cordova-plugin-network-information/doc/fr/README.md new file mode 100644 index 0000000..8f2b82c --- /dev/null +++ b/plugins/cordova-plugin-network-information/doc/fr/README.md @@ -0,0 +1,188 @@ + + +# cordova-plugin-network-information + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-network-information.svg)](https://travis-ci.org/apache/cordova-plugin-network-information) + +Ce plugin fournit une implémentation d'une ancienne version de l' [API Information Network](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/). Il fournit des informations sur l'appareil cellulaire et connexion wifi, et si l'appareil dispose d'une connexion internet. + +## Installation + + cordova plugin add cordova-plugin-network-information + + +## Plates-formes supportées + + * Amazon Fire OS + * Android + * BlackBerry 10 + * Navigateur + * iOS + * Windows Phone 7 et 8 + * Paciarelli + * Windows + * Firefox OS + +# Connexion + +> L'objet `connection`, disponible via `navigator.connection`, fournit des informations sur la connection cellulaire/wifi de l'appareil. + +## Propriétés + + * connection.type + +## Constantes + + * Connection.UNKNOWN + * Connection.ETHERNET + * Connection.WIFI + * Connection.CELL_2G + * Connection.CELL_3G + * Connection.CELL_4G + * Connection.CELL + * Connection.NONE + +## connection.type + +Cette propriété offre un moyen rapide pour déterminer l'état et le type de la connexion réseau de l'appareil. + +### Exemple court + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### Changement d'API + +Jusqu'à Cordova 2.3.0, l'objet `Connection` était accessible via `navigator.network.connection` ; ceci a été changé pour `navigator.connection` afin de concorder avec la spécification du W3C. L'accès est toujours possible à l'emplacement d'origine, mais est considéré comme obsolète et sera bientôt supprimé. + +### Notes au sujet d'iOS + + * iOS ne peut pas détecter le type de connexion au réseau cellulaire. + * `navigator.connection.type`a la valeur `Connection.CELL` pour toutes les données cellulaires. + +### Windows Phone Quirks + + * Lors de l'exécution dans l'émulateur, détecte toujours `navigator.connection.type` comme`Connection.UNKNOWN`. + + * Windows Phone ne peut pas détecter le type de connexion au réseau cellulaire. + + * `navigator.connection.type`a la valeur `Connection.CELL` pour toutes les données cellulaires. + +### Bizarreries de Windows + + * Lors de l'exécution dans l'émulateur de téléphone 8.1, `Connection.ETHERNET` détecte toujours `navigator.connection.type`. + +### Bizarreries de paciarelli + + * Paciarelli ne peut détecter une connexion cellulaire ou le WiFi. + * `navigator.connection.type` a la valeur `Connection.CELL_2G` pour toutes les données cellulaires. + +### Firefox OS Quirks + + * Firefox OS ne peut pas détecter le type de connexion au réseau cellulaire. + * `navigator.connection.type`a la valeur `Connection.CELL` pour toutes les données cellulaires. + +### Bizarreries navigateur + + * Navigateur ne peut pas détecter le type de connexion réseau. `navigator.connection.type` est toujours définie sur `Connection.UNKNOWN` en ligne. + +# Événements liés au réseau + +## offline + +L'évènement se déclenche lorsqu'une application se déconnecte, quand l'appareil n'est pas connecté à Internet. + + document.addEventListener("offline", yourCallbackFunction, false); + + +### Détails + +L'évènement `offline` se déclenche lorsqu'un appareil précédemment connecté perd sa connexion au réseau, empêchant ainsi l'application d'accéder à Internet. Il s'appuie sur les mêmes informations que l'API de connexion et se déclenche lorsque la valeur de `connection.type` devient`NONE`. + +Les applications devraient en général utiliser `document.addEventListener` pour attacher un écouteur d'évènements, une fois l'évènement `deviceready` déclenché. + +### Exemple court + + document.addEventListener (« hors ligne », onOffline, false) ; + + function onOffline() {/ / gestion de l'événement en mode hors connexion} + + +### Notes au sujet d'iOS + +Lors du démarrage initial, le déclenchement du premier évènement offline (si applicable) prend au moins une seconde. + +### Windows Phone 7 Quirks + +Lors de l'exécution dans l'émulateur, le `connection.status` est toujours inconnu, ainsi cet événement ne fait *pas* de feu. + +### Notes au sujet de Windows Phone 8 + +L'émulateur signale le type de connexion comme `Cellular`, type qui ne change jamais, ainsi l'évènement n'est *pas* déclenché. + +## online + +L'évènement se déclenche lorsqu'une application se connecte, quand l'appareil est connecté à Internet. + + document.addEventListener("online", yourCallbackFunction, false); + + +### Détails + +L'évènement `online` se déclenche lorsqu'un appareil précédemment non-connecté se connecte au réseau, permettant ainsi à l'application d'accéder à Internet. Il s'appuie sur les mêmes informations que l'API de connexion et se déclenche quand le `connection.type` passe de `NONE` à une autre valeur. + +Les applications devraient en général utiliser `document.addEventListener` pour attacher un écouteur d'évènements, une fois l'évènement `deviceready` déclenché. + +### Exemple court + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### Notes au sujet d'iOS + +Lors du démarrage initial, le déclenchement du premier évènement `online` (si applicable) prend au moins une seconde avant quoi `connection.type` vaut `UNKNOWN`. + +### Windows Phone 7 Quirks + +Lors de l'exécution dans l'émulateur, le `connection.status` est toujours inconnu, ainsi cet événement ne fait *pas* de feu. + +### Notes au sujet de Windows Phone 8 + +L'émulateur signale le type de connexion comme `Cellular` , qui ne change pas, aussi des événements ne fait *pas* de feu. \ No newline at end of file diff --git a/plugins/cordova-plugin-network-information/doc/fr/index.md b/plugins/cordova-plugin-network-information/doc/fr/index.md new file mode 100644 index 0000000..e49c5d5 --- /dev/null +++ b/plugins/cordova-plugin-network-information/doc/fr/index.md @@ -0,0 +1,184 @@ + + +# cordova-plugin-network-information + +Ce plugin fournit une implémentation d'une ancienne version de l' [API Information Network][1]. Il fournit des informations sur l'appareil cellulaire et connexion wifi, et si l'appareil dispose d'une connexion internet. + + [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ + +## Installation + + cordova plugin add cordova-plugin-network-information + + +## Plates-formes prises en charge + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Navigateur +* iOS +* Windows Phone 7 et 8 +* Paciarelli +* Windows +* Firefox OS + +# Connexion + +> L'objet `connection`, disponible via `navigator.connection`, fournit des informations sur la connection cellulaire/wifi de l'appareil. + +## Propriétés + +* connection.type + +## Constantes + +* Connection.UNKNOWN +* Connection.ETHERNET +* Connection.WIFI +* Connection.CELL_2G +* Connection.CELL_3G +* Connection.CELL_4G +* Connection.CELL +* Connection.NONE + +## connection.type + +Cette propriété offre un moyen rapide pour déterminer l'état et le type de la connexion réseau de l'appareil. + +### Petit exemple + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### Changement d'API + +Jusqu'à Cordova 2.3.0, l'objet `Connection` était accessible via `navigator.network.connection` ; ceci a été changé pour `navigator.connection` afin de concorder avec la spécification du W3C. L'accès est toujours possible à l'emplacement d'origine, mais est considéré comme obsolète et sera bientôt supprimé. + +### iOS Quirks + +* iOS ne peut pas détecter le type de connexion au réseau cellulaire. + * `navigator.connection.type`a la valeur `Connection.CELL` pour toutes les données cellulaires. + +### Windows Phone Quirks + +* Lors de l'exécution dans l'émulateur, détecte toujours `navigator.connection.type` comme`Connection.UNKNOWN`. + +* Windows Phone ne peut pas détecter le type de connexion au réseau cellulaire. + + * `navigator.connection.type`a la valeur `Connection.CELL` pour toutes les données cellulaires. + +### Bizarreries de Windows + +* Lors de l'exécution dans l'émulateur de téléphone 8.1, `Connection.ETHERNET` détecte toujours `navigator.connection.type`. + +### Bizarreries de paciarelli + +* Paciarelli ne peut détecter une connexion cellulaire ou le WiFi. + * `navigator.connection.type` a la valeur `Connection.CELL_2G` pour toutes les données cellulaires. + +### Firefox OS Quirks + +* Firefox OS ne peut pas détecter le type de connexion au réseau cellulaire. + * `navigator.connection.type` a la valeur `Connection.CELL` pour toutes les données cellulaires. + +# Événements liés au réseau + +## offline + +L'évènement se déclenche lorsqu'une application se déconnecte, quand l'appareil n'est pas connecté à Internet. + + document.addEventListener("offline", yourCallbackFunction, false); + + +### Détails + +L'évènement `offline` se déclenche lorsqu'un appareil précédemment connecté perd sa connexion au réseau, empêchant ainsi l'application d'accéder à Internet. Il s'appuie sur les mêmes informations que l'API de connexion et se déclenche lorsque la valeur de `connection.type` devient`NONE`. + +Les applications doivent généralement utiliser `document.addEventListener` pour attacher un écouteur d'événements une fois le `deviceready` événement se déclenche. + +### Exemple court + + document.addEventListener (« hors ligne », onOffline, false) ; + + function onOffline() {/ / gestion de l'événement en mode hors connexion} + + +### Notes au sujet d'iOS + +Lors du démarrage initial, le déclenchement du premier évènement offline (si applicable) prend au moins une seconde. + +### Windows Phone 7 Quirks + +Lors de l'exécution dans l'émulateur, le `connection.status` est toujours inconnu, ainsi cet événement ne fait *pas* de feu. + +### Notes au sujet de Windows Phone 8 + +L'émulateur signale le type de connexion comme `Cellular`, type qui ne change jamais, ainsi l'évènement n'est *pas* déclenché. + +## online + +L'évènement se déclenche lorsqu'une application se connecte, quand l'appareil est connecté à Internet. + + document.addEventListener("online", yourCallbackFunction, false); + + +### Détails + +L'évènement `online` se déclenche lorsqu'un appareil précédemment non-connecté se connecte au réseau, permettant ainsi à l'application d'accéder à Internet. Il s'appuie sur les mêmes informations que l'API de connexion et se déclenche quand le `connection.type` passe de `NONE` à une autre valeur. + +Les applications doivent généralement utiliser `document.addEventListener` pour attacher un écouteur d'événements une fois le `deviceready` événement se déclenche. + +### Exemple court + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### Notes au sujet d'iOS + +Lors du démarrage initial, le déclenchement du premier évènement `online` (si applicable) prend au moins une seconde avant quoi `connection.type` vaut `UNKNOWN`. + +### Windows Phone 7 Quirks + +Lors de l'exécution dans l'émulateur, le `connection.status` est toujours inconnu, ainsi cet événement ne fait *pas* de feu. + +### Notes au sujet de Windows Phone 8 + +L'émulateur signale le type de connexion comme `Cellular` , qui ne change pas, aussi des événements ne fait *pas* de feu. diff --git a/plugins/cordova-plugin-network-information/doc/it/README.md b/plugins/cordova-plugin-network-information/doc/it/README.md new file mode 100644 index 0000000..f434359 --- /dev/null +++ b/plugins/cordova-plugin-network-information/doc/it/README.md @@ -0,0 +1,190 @@ + + +# cordova-plugin-network-information + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-network-information.svg)](https://travis-ci.org/apache/cordova-plugin-network-information) + +Questo plugin fornisce un'implementazione di una vecchia versione dell' [API di informazioni di rete](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/). Fornisce informazioni sul dispositivo cellulare e connessione wifi, e se il dispositivo dispone di una connessione internet. + +## Installazione + + cordova plugin add cordova-plugin-network-information + + +## Piattaforme supportate + + * Amazon fuoco OS + * Android + * BlackBerry 10 + * Browser + * iOS + * Windows Phone 7 e 8 + * Tizen + * Windows + * Firefox OS + +# Connessione + +> Il `connection` oggetto, esposto tramite `navigator.connection` , fornisce informazioni sulla connessione wifi e cellulare del dispositivo. + +## Proprietà + + * connection.type + +## Costanti + + * Connection.UNKNOWN + * Connection.ETHERNET + * Connection.WIFI + * Connection.CELL_2G + * Connection.CELL_3G + * Connection.CELL_4G + * Connection.CELL + * Connection.NONE + +## connection.type + +Questa proprietà offre un modo rapido per determinare stato della connessione di rete del dispositivo e il tipo di connessione. + +### Esempio rapido + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### Cambiamento di API + +Fino a Cordova 2.3.0, il `Connection` oggetto era accessibile tramite `navigator.network.connection` , dopo che è stato cambiato in `navigator.connection` per abbinare la specifica W3C. È ancora disponibile nella sua posizione originale, ma è obsoleto e verrà rimosso alla fine. + +### iOS stranezze + + * iOS non è possibile rilevare il tipo di connessione di rete cellulare. + * `navigator.connection.type`è impostata su `Connection.CELL` per tutti i dati cellulare. + +### Stranezze di Windows Phone + + * Quando è in esecuzione nell'emulatore, rileva sempre `navigator.connection.type` come`Connection.UNKNOWN`. + + * Windows Phone non riesce a rilevare il tipo di connessione di rete cellulare. + + * `navigator.connection.type`è impostata su `Connection.CELL` per tutti i dati cellulare. + +### Stranezze di Windows + + * Quando è in esecuzione nell'emulatore Phone 8.1, sempre rileva `navigator.connection.type` come `Connection.ETHERNET`. + +### Tizen stranezze + + * Tizen può rilevare solo un WiFi o una connessione cellulare. + * `navigator.connection.type` è impostata su `Connection.CELL_2G` per tutti i dati cellulare. + +### Firefox OS stranezze + + * Sistema operativo Firefox non riesce a rilevare il tipo di connessione di rete cellulare. + * `navigator.connection.type`è impostata su `Connection.CELL` per tutti i dati cellulare. + +### Stranezze browser + + * Browser non è in grado di rilevare il tipo di connessione di rete. `navigator.connection.type` è sempre impostata su `Connection.UNKNOWN` quando si è online. + +# Eventi relativi alla rete + +## offline + +L'evento viene generato quando un'applicazione passa alla modalità offline, e il dispositivo non è connesso a Internet. + + document.addEventListener("offline", yourCallbackFunction, false); + + +### Dettagli + +Il `offline` evento viene generato quando un dispositivo precedentemente connesso perde una connessione di rete in modo che un'applicazione non è più possibile accedere a Internet. Esso si basa sulle stesse informazioni come l'API di connessione e viene generato quando il valore di `connection.type` diventa`NONE`. + +Applicazioni in genere è necessario utilizzare `document.addEventListener` per fissare un listener di eventi una volta il `deviceready` evento incendi. + +### Esempio rapido + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### iOS stranezze + +Durante l'avvio iniziale, il primo evento offline (se applicabile) richiede almeno un secondo al fuoco. + +### Windows Phone 7 capricci + +Quando è in esecuzione nell'emulatore, il `connection.status` è sempre sconosciuto, così fa di questo evento *non* fuoco. + +### Windows Phone 8 stranezze + +L'emulatore riporta il tipo di connessione come `Cellular` , che non cambia, così fa l'evento *non* fuoco. + +## online + +Questo evento viene generato quando un'applicazione va online, e il dispositivo diventa collegato a Internet. + + document.addEventListener("online", yourCallbackFunction, false); + + +### Dettagli + +Il `online` evento viene generato quando un dispositivo precedentemente scollegato riceve una connessione di rete per consentire un'accesso di applicazione a Internet. Esso si basa sulle stesse informazioni come l'API di connessione e viene attivato quando il `connection.type` cambia da `NONE` a qualsiasi altro valore. + +Applicazioni in genere è necessario utilizzare `document.addEventListener` per fissare un listener di eventi una volta il `deviceready` evento incendi. + +### Esempio rapido + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### iOS stranezze + +Durante l'avvio iniziale, il primo `online` evento (se applicabile) richiede almeno un secondo al fuoco, prima che `connection.type` è`UNKNOWN`. + +### Windows Phone 7 capricci + +Quando è in esecuzione nell'emulatore, il `connection.status` è sempre sconosciuto, così fa di questo evento *non* fuoco. + +### Windows Phone 8 stranezze + +L'emulatore riporta il tipo di connessione come `Cellular` , che non cambia, quindi, non gli eventi *non* a fuoco. \ No newline at end of file diff --git a/plugins/cordova-plugin-network-information/doc/it/index.md b/plugins/cordova-plugin-network-information/doc/it/index.md new file mode 100644 index 0000000..e191719 --- /dev/null +++ b/plugins/cordova-plugin-network-information/doc/it/index.md @@ -0,0 +1,186 @@ + + +# cordova-plugin-network-information + +Questo plugin fornisce un'implementazione di una vecchia versione dell' [API di informazioni di rete][1]. Fornisce informazioni sul dispositivo cellulare e connessione wifi, e se il dispositivo dispone di una connessione internet. + + [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ + +## Installazione + + cordova plugin add cordova-plugin-network-information + + +## Piattaforme supportate + +* Amazon fuoco OS +* Android +* BlackBerry 10 +* Browser +* iOS +* Windows Phone 7 e 8 +* Tizen +* Windows +* Firefox OS + +# Connessione + +> Il `connection` oggetto, esposto tramite `navigator.connection` , fornisce informazioni sulla connessione wifi e cellulare del dispositivo. + +## Proprietà + +* connection.type + +## Costanti + +* Connection.UNKNOWN +* Connection.ETHERNET +* Connection.WIFI +* Connection.CELL_2G +* Connection.CELL_3G +* Connection.CELL_4G +* Connection.CELL +* Connection.NONE + +## connection.type + +Questa proprietà offre un modo rapido per determinare stato della connessione di rete del dispositivo e il tipo di connessione. + +### Esempio rapido + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### Cambiamento di API + +Fino a Cordova 2.3.0, il `Connection` oggetto era accessibile tramite `navigator.network.connection` , dopo che è stato cambiato in `navigator.connection` per abbinare la specifica W3C. È ancora disponibile nella sua posizione originale, ma è obsoleto e verrà rimosso alla fine. + +### iOS stranezze + +* iOS non è possibile rilevare il tipo di connessione di rete cellulare. + * `navigator.connection.type`è impostata su `Connection.CELL` per tutti i dati cellulare. + +### Stranezze di Windows Phone + +* Quando è in esecuzione nell'emulatore, rileva sempre `navigator.connection.type` come`Connection.UNKNOWN`. + +* Windows Phone non riesce a rilevare il tipo di connessione di rete cellulare. + + * `navigator.connection.type`è impostata su `Connection.CELL` per tutti i dati cellulare. + +### Stranezze di Windows + +* Quando è in esecuzione nell'emulatore Phone 8.1, sempre rileva `navigator.connection.type` come `Connection.ETHERNET`. + +### Tizen stranezze + +* Tizen può rilevare solo un WiFi o una connessione cellulare. + * `navigator.connection.type` è impostata su `Connection.CELL_2G` per tutti i dati cellulare. + +### Firefox OS stranezze + +* Sistema operativo Firefox non riesce a rilevare il tipo di connessione di rete cellulare. + * `navigator.connection.type`è impostata su `Connection.CELL` per tutti i dati cellulare. + +# Eventi relativi alla rete + +## offline + +L'evento viene generato quando un'applicazione passa alla modalità offline, e il dispositivo non è connesso a Internet. + + document.addEventListener("offline", yourCallbackFunction, false); + + +### Dettagli + +Il `offline` evento viene generato quando un dispositivo precedentemente connesso perde una connessione di rete in modo che un'applicazione non è più possibile accedere a Internet. Esso si basa sulle stesse informazioni come l'API di connessione e viene generato quando il valore di `connection.type` diventa`NONE`. + +Applicazioni in genere è necessario utilizzare `document.addEventListener` per fissare un listener di eventi una volta il `deviceready` evento incendi. + +### Esempio rapido + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### iOS stranezze + +Durante l'avvio iniziale, il primo evento offline (se applicabile) richiede almeno un secondo al fuoco. + +### Windows Phone 7 capricci + +Quando è in esecuzione nell'emulatore, il `connection.status` è sempre sconosciuto, così fa di questo evento *non* fuoco. + +### Windows Phone 8 stranezze + +L'emulatore riporta il tipo di connessione come `Cellular` , che non cambia, così fa l'evento *non* fuoco. + +## online + +Questo evento viene generato quando un'applicazione va online, e il dispositivo diventa collegato a Internet. + + document.addEventListener("online", yourCallbackFunction, false); + + +### Dettagli + +Il `online` evento viene generato quando un dispositivo precedentemente scollegato riceve una connessione di rete per consentire un'accesso di applicazione a Internet. Esso si basa sulle stesse informazioni come l'API di connessione e viene attivato quando il `connection.type` cambia da `NONE` a qualsiasi altro valore. + +Applicazioni in genere è necessario utilizzare `document.addEventListener` per fissare un listener di eventi una volta il `deviceready` evento incendi. + +### Esempio rapido + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### iOS stranezze + +Durante l'avvio iniziale, il primo `online` evento (se applicabile) richiede almeno un secondo al fuoco, prima che `connection.type` è`UNKNOWN`. + +### Windows Phone 7 capricci + +Quando è in esecuzione nell'emulatore, il `connection.status` è sempre sconosciuto, così fa di questo evento *non* fuoco. + +### Windows Phone 8 stranezze + +L'emulatore riporta il tipo di connessione come `Cellular` , che non cambia, quindi, non gli eventi *non* a fuoco. diff --git a/plugins/cordova-plugin-network-information/doc/ja/README.md b/plugins/cordova-plugin-network-information/doc/ja/README.md new file mode 100644 index 0000000..797b741 --- /dev/null +++ b/plugins/cordova-plugin-network-information/doc/ja/README.md @@ -0,0 +1,190 @@ + + +# cordova-plugin-network-information + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-network-information.svg)](https://travis-ci.org/apache/cordova-plugin-network-information) + +このプラグインは、古いバージョンの[ネットワーク情報 API](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/)の実装を提供します。 デバイスの携帯電話や wifi 接続に関する情報を提供し、かどうか、デバイスがインターネットに接続します。 + +## インストール + + cordova plugin add cordova-plugin-network-information + + +## サポートされているプラットフォーム + + * アマゾン火 OS + * アンドロイド + * ブラックベリー 10 + * ブラウザー + * iOS + * Windows Phone 7 と 8 + * Tizen + * Windows + * Firefox の OS + +# Connection + +> `connection`オブジェクトによって公開されて `navigator.connection` 、デバイスの携帯電話や wifi 接続に関する情報を提供します。 + +## プロパティ + + * connection.type + +## 定数 + + * Connection.UNKNOWN + * Connection.ETHERNET + * Connection.WIFI + * Connection.CELL_2G + * Connection.CELL_3G + * Connection.CELL_4G + * Connection.CELL + * Connection.NONE + +## connection.type + +このプロパティはデバイスのネットワーク接続状態を確認する速い方法を提供し、接続の種類。 + +### 簡単な例 + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### API の変更 + +コルドバ 2.3.0、まで、 `Connection` 経由でアクセスされたオブジェクトが `navigator.network.connection` 、それに変更されましたが後 `navigator.connection` W3C の仕様に一致します。 それはまだ元の場所は廃止され、最終的に削除されます。 + +### iOS の癖 + + * iOS は、携帯電話のネットワーク接続の種類を検出できません。 + * `navigator.connection.type`設定する `Connection.CELL` すべての携帯電話データの。 + +### Windows Phone の癖 + + * エミュレーターで実行しているときを常に検出 `navigator.connection.type` として`Connection.UNKNOWN`. + + * Windows Phone 携帯電話ネットワーク接続の種類を検出できません。 + + * `navigator.connection.type`設定する `Connection.CELL` すべての携帯電話データの。 + +### Windows の癖 + + * 電話 8.1 エミュレーターで実行する場合は、常に `Connection.ETHERNET` として `navigator.connection.type` を検出します. + +### Tizen の癖 + + * Tizen には、WiFi または携帯電話の接続だけを検出できます。 + * `navigator.connection.type` は、すべての携帯電話のデータを `Connection.CELL_2G` に設定されます。 + +### Firefox OS 癖 + + * Firefox の OS は、携帯電話のネットワーク接続の種類を検出できません。 + * `navigator.connection.type`設定する `Connection.CELL` すべての携帯電話データの。 + +### ブラウザーの癖 + + * ブラウザーは、ネットワーク接続の種類を検出できません。 `navigator.connection.type`は、 `Connection.UNKNOWN`オンライン時に常に設定されます。 + +# ネットワーク関連のイベント + +## offline + +アプリケーションがオフラインになり、デバイスがインターネットに接続されていないときに発生します。 + + document.addEventListener("offline", yourCallbackFunction, false); + + +### 詳細 + +`offline`アプリケーションはもはや、インターネットにアクセスできるように、以前接続されたデバイスは、ネットワーク接続が失われたときに発生します。 接続 API と同じ情報に依存しており、火災時の値 `connection.type` になります。`NONE`. + +通常アプリケーションに使用する必要があります `document.addEventListener` 一度のイベント リスナーをアタッチし、 `deviceready` イベントが発生します。 + +### 簡単な例 + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### iOS の癖 + +初回起動時 (当てはまる場合) の最初のオフライン イベントは火に 1 秒以上かかります。 + +### Windows Phone 7 の癖 + +エミュレーターで実行しているとき、 `connection.status` は常に知られている、このイベントは*ない*火。 + +### Windows Phone 8 癖 + +エミュレーターと接続の種類のレポート `Cellular` は変化しません、イベントは*ない*火。 + +## online + +アプリケーションは、オンラインになるし、デバイスがインターネットに接続するときに発生します。 + + document.addEventListener("online", yourCallbackFunction, false); + + +### 詳細 + +`online`以前接続されていないデバイスが、インターネットへのアプリケーション アクセスを許可するネットワーク接続を受信するときに発生します。 接続 API と同じ情報に依存しており、場合に適用されます、 `connection.type` から変更 `NONE` 以外の値にします。 + +通常アプリケーションに使用する必要があります `document.addEventListener` 一度のイベント リスナーをアタッチし、 `deviceready` イベントが発生します。 + +### 簡単な例 + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### iOS の癖 + +初回起動時には、最初の `online` (当てはまる場合) イベントが少なくとも火を前に第 2 `connection.type` は`UNKNOWN`. + +### Windows Phone 7 の癖 + +エミュレーターで実行しているとき、 `connection.status` は常に知られている、このイベントは*ない*火。 + +### Windows Phone 8 癖 + +エミュレーターと接続の種類のレポート `Cellular` は変化しません、イベントは*ない*火。 \ No newline at end of file diff --git a/plugins/cordova-plugin-network-information/doc/ja/index.md b/plugins/cordova-plugin-network-information/doc/ja/index.md new file mode 100644 index 0000000..71b6f82 --- /dev/null +++ b/plugins/cordova-plugin-network-information/doc/ja/index.md @@ -0,0 +1,186 @@ + + +# cordova-plugin-network-information + +このプラグインは、古いバージョンの[ネットワーク情報 API][1]の実装を提供します。 デバイスの携帯電話や wifi 接続に関する情報を提供し、かどうか、デバイスがインターネットに接続します。 + + [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ + +## インストール + + cordova plugin add cordova-plugin-network-information + + +## サポートされているプラットフォーム + +* アマゾン火 OS +* アンドロイド +* ブラックベリー 10 +* ブラウザー +* iOS +* Windows Phone 7 と 8 +* Tizen +* Windows +* Firefox の OS + +# Connection + +> `connection`オブジェクトによって公開されて `navigator.connection` 、デバイスの携帯電話や wifi 接続に関する情報を提供します。 + +## プロパティ + +* connection.type + +## 定数 + +* Connection.UNKNOWN +* Connection.ETHERNET +* Connection.WIFI +* Connection.CELL_2G +* Connection.CELL_3G +* Connection.CELL_4G +* Connection.CELL +* Connection.NONE + +## connection.type + +このプロパティはデバイスのネットワーク接続状態を確認する速い方法を提供し、接続の種類。 + +### 簡単な例 + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### API の変更 + +コルドバ 2.3.0、まで、 `Connection` 経由でアクセスされたオブジェクトが `navigator.network.connection` 、それに変更されましたが後 `navigator.connection` W3C の仕様に一致します。 それはまだ元の場所は廃止され、最終的に削除されます。 + +### iOS の癖 + +* iOS は、携帯電話のネットワーク接続の種類を検出できません。 + * `navigator.connection.type`設定する `Connection.CELL` すべての携帯電話データの。 + +### Windows Phone の癖 + +* エミュレーターで実行しているときを常に検出 `navigator.connection.type` として`Connection.UNKNOWN`. + +* Windows Phone 携帯電話ネットワーク接続の種類を検出できません。 + + * `navigator.connection.type`設定する `Connection.CELL` すべての携帯電話データの。 + +### Windows の癖 + +* 電話 8.1 エミュレーターで実行する場合は、常に `Connection.ETHERNET` として `navigator.connection.type` を検出します. + +### Tizen の癖 + +* Tizen には、WiFi または携帯電話の接続だけを検出できます。 + * `navigator.connection.type` は、すべての携帯電話のデータを `Connection.CELL_2G` に設定されます。 + +### Firefox OS 癖 + +* Firefox の OS は、携帯電話のネットワーク接続の種類を検出できません。 + * `navigator.connection.type`設定する `Connection.CELL` すべての携帯電話データの。 + +# ネットワーク関連のイベント + +## offline + +アプリケーションがオフラインになり、デバイスがインターネットに接続されていないときに発生します。 + + document.addEventListener("offline", yourCallbackFunction, false); + + +### 詳細 + +`offline`アプリケーションはもはや、インターネットにアクセスできるように、以前接続されたデバイスは、ネットワーク接続が失われたときに発生します。 接続 API と同じ情報に依存しており、火災時の値 `connection.type` になります。`NONE`. + +通常アプリケーションに使用する必要があります `document.addEventListener` 一度のイベント リスナーをアタッチし、 `deviceready` イベントが発生します。 + +### 簡単な例 + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### iOS の癖 + +初回起動時 (当てはまる場合) の最初のオフライン イベントは火に 1 秒以上かかります。 + +### Windows Phone 7 の癖 + +エミュレーターで実行しているとき、 `connection.status` は常に知られている、このイベントは*ない*火。 + +### Windows Phone 8 癖 + +エミュレーターと接続の種類のレポート `Cellular` は変化しません、イベントは*ない*火。 + +## online + +アプリケーションは、オンラインになるし、デバイスがインターネットに接続するときに発生します。 + + document.addEventListener("online", yourCallbackFunction, false); + + +### 詳細 + +`online`以前接続されていないデバイスが、インターネットへのアプリケーション アクセスを許可するネットワーク接続を受信するときに発生します。 接続 API と同じ情報に依存しており、場合に適用されます、 `connection.type` から変更 `NONE` 以外の値にします。 + +通常アプリケーションに使用する必要があります `document.addEventListener` 一度のイベント リスナーをアタッチし、 `deviceready` イベントが発生します。 + +### 簡単な例 + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### iOS の癖 + +初回起動時には、最初の `online` (当てはまる場合) イベントが少なくとも火を前に第 2 `connection.type` は`UNKNOWN`. + +### Windows Phone 7 の癖 + +エミュレーターで実行しているとき、 `connection.status` は常に知られている、このイベントは*ない*火。 + +### Windows Phone 8 癖 + +エミュレーターと接続の種類のレポート `Cellular` は変化しません、イベントは*ない*火。 diff --git a/plugins/cordova-plugin-network-information/doc/ko/README.md b/plugins/cordova-plugin-network-information/doc/ko/README.md new file mode 100644 index 0000000..a667539 --- /dev/null +++ b/plugins/cordova-plugin-network-information/doc/ko/README.md @@ -0,0 +1,190 @@ + + +# cordova-plugin-network-information + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-network-information.svg)](https://travis-ci.org/apache/cordova-plugin-network-information) + +이 플러그인 [네트워크 정보 API](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/)의 이전 버전에 대 한 구현을 제공합니다. 소자의 셀룰러와 와이파이 연결에 대 한 정보를 제공 합니다 장치는 인터넷 연결에 있는지 여부. + +## 설치 + + cordova plugin add cordova-plugin-network-information + + +## 지원 되는 플랫폼 + + * 아마존 화재 운영 체제 + * 안 드 로이드 + * 블랙베리 10 + * 브라우저 + * iOS + * Windows Phone 7과 8 + * Tizen + * 윈도우 + * Firefox 운영 체제 + +# 연결 + +> `connection`개체를 통해 노출 `navigator.connection` , 소자의 셀룰러와 와이파이 연결에 대 한 정보를 제공 합니다. + +## 속성 + + * connection.type + +## 상수 + + * Connection.UNKNOWN + * Connection.ETHERNET + * Connection.WIFI + * Connection.CELL_2G + * Connection.CELL_3G + * Connection.CELL_4G + * Connection.CELL + * Connection.NONE + +## connection.type + +이 디바이스의 네트워크 연결 상태를 확인 하는 빠른 방법을 제공 합니다 및 연결의 종류. + +### 빠른 예제 + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### API 변경 + +코르 도우 바 2.3.0까지 `Connection` 개체를 통해 액세스 했습니다 `navigator.network.connection` , 후에 변경 된 `navigator.connection` W3C 사양에 맞게. 그것은 그것의 원래 위치에 계속 사용할 수 하지만 사용 되지 않습니다 및 결국 제거 될 것 이다. + +### iOS 단점 + + * iOS는 셀룰러 네트워크 연결의 종류를 감지할 수 없습니다. + * `navigator.connection.type`로 설정 된 `Connection.CELL` 모든 셀룰러 데이터에 대 한. + +### Windows Phone 단점 + + * 에뮬레이터에서 실행할 때 항상 검색 `navigator.connection.type` 으로`Connection.UNKNOWN`. + + * Windows Phone 셀룰러 네트워크 연결 유형을 검색할 수 없습니다. + + * `navigator.connection.type`로 설정 된 `Connection.CELL` 모든 셀룰러 데이터에 대 한. + +### 윈도우 특수 + + * 전화 8.1 에뮬레이터에서 실행 하는 경우 항상 `Connection.ETHERNET`로 `navigator.connection.type`를 감지합니다. + +### Tizen 특수 + + * Tizen은 와이파이 또는 휴대 전화 연결에만 검색할 수 있습니다. + * `navigator.connection.type`는 모든 셀룰러 데이터에 대 한 `Connection.CELL_2G`로 설정 됩니다. + +### 파이어 폭스 OS 단점 + + * 파이어 폭스 OS 셀룰러 네트워크 연결 유형을 검색할 수 없습니다. + * `navigator.connection.type`로 설정 된 `Connection.CELL` 모든 셀룰러 데이터에 대 한. + +### 브라우저 만지면 + + * 브라우저는 네트워크 연결의 종류를 검색할 수 없습니다. `navigator.connection.type` `Connection.UNKNOWN` 때 온라인으로 항상 설정 됩니다. + +# 네트워크 관련 이벤트 + +## offline + +이벤트가 발생 하면 응용 프로그램 오프 라인, 이동 및 장치가 인터넷에 연결 되어 있지. + + document.addEventListener("offline", yourCallbackFunction, false); + + +### 세부 정보 + +`offline`이벤트가 발생 하면 응용 프로그램이 더 이상 인터넷에 액세스할 수 있도록 이전 연결 된 장치가 네트워크 연결 손실. 그것은 연결 API와 동일한 정보에 의존 하 고 경우의 값 `connection.type` 된다`NONE`. + +일반적으로 응용 프로그램을 사용 해야 합니다 `document.addEventListener` 한번 이벤트 리스너를 연결 하는 `deviceready` 이벤트가 발생 합니다. + +### 빠른 예제 + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### iOS 단점 + +처음 시작 하는 동안 첫 번째 오프 라인 이벤트 (있는 경우)를 적어도 초를 걸립니다. + +### Windows Phone 7 단점 + +에뮬레이터에서 실행 하는 경우는 `connection.status` 항상 불명 하다, 그래서이 이벤트는 *없는* 불. + +### Windows Phone 8 단점 + +에뮬레이터도 연결 형식을 보고 `Cellular` 는 변경 되지 않습니다, 그래서 이벤트 않습니다 *하지* 불. + +## online + +응용 프로그램은 온라인 및 장치가 인터넷에 연결 된다 때이 이벤트가 발생 합니다. + + document.addEventListener("online", yourCallbackFunction, false); + + +### 세부 정보 + +`online`이전 연결 되지 않은 장치는 인터넷에 대 한 응용 프로그램 액세스를 허용 하도록 네트워크 연결을 받을 때 이벤트가 발생 합니다. 그것은 연결 API와 동일한 정보에 의존 하 고 경우에 `connection.type` 에서 변경 `NONE` 다른 값으로. + +일반적으로 응용 프로그램을 사용 해야 합니다 `document.addEventListener` 한번 이벤트 리스너를 연결 하는 `deviceready` 이벤트가 발생 합니다. + +### 빠른 예제 + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### iOS 단점 + +처음 시작 하는 동안 첫 번째 `online` 이벤트 (있는 경우) 이전에 불 초 걸립니다 이상 `connection.type` 입니다`UNKNOWN`. + +### Windows Phone 7 단점 + +에뮬레이터에서 실행 하는 경우는 `connection.status` 항상 불명 하다, 그래서이 이벤트는 *없는* 불. + +### Windows Phone 8 단점 + +에뮬레이터도 연결 형식을 보고 `Cellular` 는 변경 되지 않습니다, 그래서 이벤트 않습니다 *하지* 불. \ No newline at end of file diff --git a/plugins/cordova-plugin-network-information/doc/ko/index.md b/plugins/cordova-plugin-network-information/doc/ko/index.md new file mode 100644 index 0000000..cb4c727 --- /dev/null +++ b/plugins/cordova-plugin-network-information/doc/ko/index.md @@ -0,0 +1,186 @@ + + +# cordova-plugin-network-information + +이 플러그인 [네트워크 정보 API][1]의 이전 버전에 대 한 구현을 제공합니다. 소자의 셀룰러와 와이파이 연결에 대 한 정보를 제공 합니다 장치는 인터넷 연결에 있는지 여부. + + [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ + +## 설치 + + cordova plugin add cordova-plugin-network-information + + +## 지원 되는 플랫폼 + +* 아마존 화재 운영 체제 +* 안 드 로이드 +* 블랙베리 10 +* 브라우저 +* iOS +* Windows Phone 7과 8 +* Tizen +* 윈도우 +* Firefox 운영 체제 + +# 연결 + +> `connection`개체를 통해 노출 `navigator.connection` , 소자의 셀룰러와 와이파이 연결에 대 한 정보를 제공 합니다. + +## 속성 + +* connection.type + +## 상수 + +* Connection.UNKNOWN +* Connection.ETHERNET +* Connection.WIFI +* Connection.CELL_2G +* Connection.CELL_3G +* Connection.CELL_4G +* Connection.CELL +* Connection.NONE + +## connection.type + +이 디바이스의 네트워크 연결 상태를 확인 하는 빠른 방법을 제공 합니다 및 연결의 종류. + +### 빠른 예제 + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### API 변경 + +코르 도우 바 2.3.0까지 `Connection` 개체를 통해 액세스 했습니다 `navigator.network.connection` , 후에 변경 된 `navigator.connection` W3C 사양에 맞게. 그것은 그것의 원래 위치에 계속 사용할 수 하지만 사용 되지 않습니다 및 결국 제거 될 것 이다. + +### iOS 단점 + +* iOS는 셀룰러 네트워크 연결의 종류를 감지할 수 없습니다. + * `navigator.connection.type`로 설정 된 `Connection.CELL` 모든 셀룰러 데이터에 대 한. + +### Windows Phone 단점 + +* 에뮬레이터에서 실행할 때 항상 검색 `navigator.connection.type` 으로`Connection.UNKNOWN`. + +* Windows Phone 셀룰러 네트워크 연결 유형을 검색할 수 없습니다. + + * `navigator.connection.type`로 설정 된 `Connection.CELL` 모든 셀룰러 데이터에 대 한. + +### 윈도우 특수 + +* 전화 8.1 에뮬레이터에서 실행 하는 경우 항상 `Connection.ETHERNET`로 `navigator.connection.type`를 감지합니다. + +### Tizen 특수 + +* Tizen은 와이파이 또는 휴대 전화 연결에만 검색할 수 있습니다. + * `navigator.connection.type`는 모든 셀룰러 데이터에 대 한 `Connection.CELL_2G`로 설정 됩니다. + +### 파이어 폭스 OS 단점 + +* 파이어 폭스 OS 셀룰러 네트워크 연결 유형을 검색할 수 없습니다. + * `navigator.connection.type`로 설정 된 `Connection.CELL` 모든 셀룰러 데이터에 대 한. + +# 네트워크 관련 이벤트 + +## offline + +이벤트가 발생 하면 응용 프로그램 오프 라인, 이동 및 장치가 인터넷에 연결 되어 있지. + + document.addEventListener("offline", yourCallbackFunction, false); + + +### 세부 정보 + +`offline`이벤트가 발생 하면 응용 프로그램이 더 이상 인터넷에 액세스할 수 있도록 이전 연결 된 장치가 네트워크 연결 손실. 그것은 연결 API와 동일한 정보에 의존 하 고 경우의 값 `connection.type` 된다`NONE`. + +일반적으로 응용 프로그램을 사용 해야 합니다 `document.addEventListener` 한번 이벤트 리스너를 연결 하는 `deviceready` 이벤트가 발생 합니다. + +### 빠른 예제 + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### iOS 단점 + +처음 시작 하는 동안 첫 번째 오프 라인 이벤트 (있는 경우)를 적어도 초를 걸립니다. + +### Windows Phone 7 단점 + +에뮬레이터에서 실행 하는 경우는 `connection.status` 항상 불명 하다, 그래서이 이벤트는 *없는* 불. + +### Windows Phone 8 단점 + +에뮬레이터도 연결 형식을 보고 `Cellular` 는 변경 되지 않습니다, 그래서 이벤트 않습니다 *하지* 불. + +## online + +응용 프로그램은 온라인 및 장치가 인터넷에 연결 된다 때이 이벤트가 발생 합니다. + + document.addEventListener("online", yourCallbackFunction, false); + + +### 세부 정보 + +`online`이전 연결 되지 않은 장치는 인터넷에 대 한 응용 프로그램 액세스를 허용 하도록 네트워크 연결을 받을 때 이벤트가 발생 합니다. 그것은 연결 API와 동일한 정보에 의존 하 고 경우에 `connection.type` 에서 변경 `NONE` 다른 값으로. + +일반적으로 응용 프로그램을 사용 해야 합니다 `document.addEventListener` 한번 이벤트 리스너를 연결 하는 `deviceready` 이벤트가 발생 합니다. + +### 빠른 예제 + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### iOS 단점 + +처음 시작 하는 동안 첫 번째 `online` 이벤트 (있는 경우) 이전에 불 초 걸립니다 이상 `connection.type` 입니다`UNKNOWN`. + +### Windows Phone 7 단점 + +에뮬레이터에서 실행 하는 경우는 `connection.status` 항상 불명 하다, 그래서이 이벤트는 *없는* 불. + +### Windows Phone 8 단점 + +에뮬레이터도 연결 형식을 보고 `Cellular` 는 변경 되지 않습니다, 그래서 이벤트 않습니다 *하지* 불. diff --git a/plugins/cordova-plugin-network-information/doc/pl/README.md b/plugins/cordova-plugin-network-information/doc/pl/README.md new file mode 100644 index 0000000..4b66cbb --- /dev/null +++ b/plugins/cordova-plugin-network-information/doc/pl/README.md @@ -0,0 +1,190 @@ + + +# cordova-plugin-network-information + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-network-information.svg)](https://travis-ci.org/apache/cordova-plugin-network-information) + +Wtyczka stanowi implementację starą wersję [API informacji w sieci](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/). Udostępnia informacje na temat urządzenia komórkowe i wifi połączenie, i czy urządzenie ma połączenie z Internetem. + +## Instalacja + + cordova plugin add cordova-plugin-network-information + + +## Obsługiwane platformy + + * Amazon Fire OS + * Android + * BlackBerry 10 + * Przeglądarka + * iOS + * Windows Phone 7 i 8 + * Tizen + * Windows + * Firefox OS + +# Połączenie + +> `connection`Obiektu, wystawiony przez `navigator.connection` , zawiera informacje o połączeniu urządzenia komórkowe i wifi. + +## Właściwości + + * Connection.Type + +## Stałe + + * Connection.UNKNOWN + * Connection.ETHERNET + * Connection.WIFI + * Connection.CELL_2G + * Connection.CELL_3G + * Connection.CELL_4G + * Connection.CELL + * Connection.NONE + +## Connection.Type + +Oferuje szybki sposób ustalić stan połączenia sieciowego urządzenia i typ połączenia. + +### Szybki przykład + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### Zmiana interfejsu API + +Do Cordova 2.3.0 `Connection` obiekt uzyskano za pośrednictwem `navigator.network.connection` , po którym został zmieniony na `navigator.connection` odpowiadać specyfikacji W3C. To jest nadal dostępne w jego oryginalnej lokalizacji, ale jest niezalecane i zostaną ostatecznie usunięte. + +### Dziwactwa iOS + + * iOS nie może wykryć typ połączenia w sieci komórkowej. + * `navigator.connection.type`jest zestaw `Connection.CELL` dla wszystkich komórek danych. + +### Windows Phone dziwactwa + + * Po uruchomieniu w emulatorze, zawsze wykrywa `navigator.connection.type` jako`Connection.UNKNOWN`. + + * Windows Phone nie może wykryć typ połączenia w sieci komórkowej. + + * `navigator.connection.type`jest zestaw `Connection.CELL` dla wszystkich komórek danych. + +### Windows dziwactwa + + * Po uruchomieniu w emulatorze telefonu 8.1, zawsze wykrywa `navigator.connection.type` jako `Connection.ETHERNET`. + +### Dziwactwa Tizen + + * Tizen można tylko dostrzegać Wi-Fi lub połączenia komórkowe. + * `Navigator.Connection.Type` jest zestaw do `Connection.CELL_2G` dla wszystkich komórek danych. + +### Firefox OS dziwactwa + + * Firefox OS nie można wykryć typ połączenia w sieci komórkowej. + * `navigator.connection.type`jest zestaw `Connection.CELL` dla wszystkich komórek danych. + +### Quirks przeglądarki + + * Przeglądarka nie może wykryć typ połączenia sieciowego. `Navigator.Connection.Type` jest zawsze zestaw do `Connection.UNKNOWN` podczas online. + +# Zdarzenia związane z sieci + +## offline + +Zdarzenie odpala gdy aplikacja przejdzie do trybu offline, a urządzenie nie jest podłączone do Internetu. + + document.addEventListener("offline", yourCallbackFunction, false); + + +### Szczegóły + +`offline`Zdarzenie fires po wcześniej podłączone urządzenie traci połączenia z siecią, dzięki czemu aplikacja może już dostęp do Internetu. Opiera się na te same informacje połączenia API i gdy odpalam wartość `connection.type` staje się`NONE`. + +Aplikacje zwykle należy użyć `document.addEventListener` Aby dołączyć słuchacza raz `deviceready` pożary zdarzenia. + +### Szybki przykład + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### Dziwactwa iOS + +Podczas uruchamiania systemu pierwsza impreza offline (jeśli dotyczy) trwa co najmniej drugi ognia. + +### Dziwactwa Windows Phone 7 + +Po uruchomieniu w emulatorze, `connection.status` zawsze jest nieznana, więc to wydarzenie *nie* ogień. + +### Windows Phone 8 dziwactwa + +Emulator raporty typ połączenia, jako `Cellular` , co nie zmienia, więc zdarzenie *nie* ogień. + +## online + +Wydarzenie to odpala gdy aplikacja przechodzi w tryb online i urządzenie staje się połączenie z Internetem. + + document.addEventListener("online", yourCallbackFunction, false); + + +### Szczegóły + +`online`Zdarzenie odpala gdy wcześniej niezwiązane urządzenie odbiera połączenie sieciowe, aby umożliwić aplikacji dostęp do Internetu. Opiera się na te same informacje połączenia API i gdy odpalam `connection.type` zmienia się z `NONE` na inną wartość. + +Aplikacje zwykle należy użyć `document.addEventListener` Aby dołączyć słuchacza raz `deviceready` pożary zdarzenia. + +### Szybki przykład + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### Dziwactwa iOS + +Podczas uruchamiania systemu pierwszy `online` zdarzenia (w stosownych przypadkach) zajmuje co najmniej drugie ognia, przed którym `connection.type` jest`UNKNOWN`. + +### Dziwactwa Windows Phone 7 + +Po uruchomieniu w emulatorze, `connection.status` zawsze jest nieznana, więc to wydarzenie *nie* ogień. + +### Windows Phone 8 dziwactwa + +Emulator sprawozdania jako typ połączenia `Cellular` , które nie zmienia, więc wydarzenia czy *nie* ogień. \ No newline at end of file diff --git a/plugins/cordova-plugin-network-information/doc/pl/index.md b/plugins/cordova-plugin-network-information/doc/pl/index.md new file mode 100644 index 0000000..a42b973 --- /dev/null +++ b/plugins/cordova-plugin-network-information/doc/pl/index.md @@ -0,0 +1,186 @@ + + +# cordova-plugin-network-information + +Wtyczka stanowi implementację starą wersję [API informacji w sieci][1]. Udostępnia informacje na temat urządzenia komórkowe i wifi połączenie, i czy urządzenie ma połączenie z Internetem. + + [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ + +## Instalacja + + cordova plugin add cordova-plugin-network-information + + +## Obsługiwane platformy + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Przeglądarka +* iOS +* Windows Phone 7 i 8 +* Tizen +* Windows +* Firefox OS + +# Połączenie + +> `connection`Obiektu, wystawiony przez `navigator.connection` , zawiera informacje o połączeniu urządzenia komórkowe i wifi. + +## Właściwości + +* Connection.Type + +## Stałe + +* Connection.UNKNOWN +* Connection.ETHERNET +* Connection.WIFI +* Connection.CELL_2G +* Connection.CELL_3G +* Connection.CELL_4G +* Connection.CELL +* Connection.NONE + +## Connection.Type + +Oferuje szybki sposób ustalić stan połączenia sieciowego urządzenia i typ połączenia. + +### Szybki przykład + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### Zmiana interfejsu API + +Do Cordova 2.3.0 `Connection` obiekt uzyskano za pośrednictwem `navigator.network.connection` , po którym został zmieniony na `navigator.connection` odpowiadać specyfikacji W3C. To jest nadal dostępne w jego oryginalnej lokalizacji, ale jest niezalecane i zostaną ostatecznie usunięte. + +### Dziwactwa iOS + +* iOS nie może wykryć typ połączenia w sieci komórkowej. + * `navigator.connection.type`jest zestaw `Connection.CELL` dla wszystkich komórek danych. + +### Windows Phone dziwactwa + +* Po uruchomieniu w emulatorze, zawsze wykrywa `navigator.connection.type` jako`Connection.UNKNOWN`. + +* Windows Phone nie może wykryć typ połączenia w sieci komórkowej. + + * `navigator.connection.type`jest zestaw `Connection.CELL` dla wszystkich komórek danych. + +### Windows dziwactwa + +* Po uruchomieniu w emulatorze telefonu 8.1, zawsze wykrywa `navigator.connection.type` jako `Connection.ETHERNET`. + +### Dziwactwa Tizen + +* Tizen można tylko dostrzegać Wi-Fi lub połączenia komórkowe. + * `Navigator.Connection.Type` jest zestaw do `Connection.CELL_2G` dla wszystkich komórek danych. + +### Firefox OS dziwactwa + +* Firefox OS nie można wykryć typ połączenia w sieci komórkowej. + * `navigator.connection.type`jest zestaw `Connection.CELL` dla wszystkich komórek danych. + +# Zdarzenia związane z sieci + +## offline + +Zdarzenie odpala gdy aplikacja przejdzie do trybu offline, a urządzenie nie jest podłączone do Internetu. + + document.addEventListener("offline", yourCallbackFunction, false); + + +### Szczegóły + +`offline`Zdarzenie fires po wcześniej podłączone urządzenie traci połączenia z siecią, dzięki czemu aplikacja może już dostęp do Internetu. Opiera się na te same informacje połączenia API i gdy odpalam wartość `connection.type` staje się`NONE`. + +Aplikacje zwykle należy użyć `document.addEventListener` Aby dołączyć słuchacza raz `deviceready` pożary zdarzenia. + +### Szybki przykład + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### Dziwactwa iOS + +Podczas uruchamiania systemu pierwsza impreza offline (jeśli dotyczy) trwa co najmniej drugi ognia. + +### Dziwactwa Windows Phone 7 + +Po uruchomieniu w emulatorze, `connection.status` zawsze jest nieznana, więc to wydarzenie *nie* ogień. + +### Windows Phone 8 dziwactwa + +Emulator raporty typ połączenia, jako `Cellular` , co nie zmienia, więc zdarzenie *nie* ogień. + +## online + +Wydarzenie to odpala gdy aplikacja przechodzi w tryb online i urządzenie staje się połączenie z Internetem. + + document.addEventListener("online", yourCallbackFunction, false); + + +### Szczegóły + +`online`Zdarzenie odpala gdy wcześniej niezwiązane urządzenie odbiera połączenie sieciowe, aby umożliwić aplikacji dostęp do Internetu. Opiera się na te same informacje połączenia API i gdy odpalam `connection.type` zmienia się z `NONE` na inną wartość. + +Aplikacje zwykle należy użyć `document.addEventListener` Aby dołączyć słuchacza raz `deviceready` pożary zdarzenia. + +### Szybki przykład + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### Dziwactwa iOS + +Podczas uruchamiania systemu pierwszy `online` zdarzenia (w stosownych przypadkach) zajmuje co najmniej drugie ognia, przed którym `connection.type` jest`UNKNOWN`. + +### Dziwactwa Windows Phone 7 + +Po uruchomieniu w emulatorze, `connection.status` zawsze jest nieznana, więc to wydarzenie *nie* ogień. + +### Windows Phone 8 dziwactwa + +Emulator sprawozdania jako typ połączenia `Cellular` , które nie zmienia, więc wydarzenia czy *nie* ogień. diff --git a/plugins/cordova-plugin-network-information/doc/ru/index.md b/plugins/cordova-plugin-network-information/doc/ru/index.md new file mode 100644 index 0000000..481c1b1 --- /dev/null +++ b/plugins/cordova-plugin-network-information/doc/ru/index.md @@ -0,0 +1,182 @@ + + +# cordova-plugin-network-information + +Этот плагин обеспечивает реализацию старой версии [API Сетевой информации][1]. Он предоставляет информацию о сотовых и Wi-Fi подключениях устройства, и информацию имеет ли устройство подключение к Интернету. + + [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ + +## Установка + + cordova plugin add cordova-plugin-network-information + + +## Поддерживаемые платформы + +* Amazon Fire OS +* Android +* BlackBerry 10 +* Браузер +* iOS +* Windows Phone 7 и 8 +* Tizen +* Windows 8 +* Firefox OS + +# Connection + +> Объект `connection`, доступный через `navigator.connection`, предоставляет информацию о сотовых и wifi подключениях устройства. + +## Свойства + +* connection.type + +## Константы + +* Connection.UNKNOWN +* Connection.ETHERNET +* Connection.WIFI +* Connection.CELL_2G +* Connection.CELL_3G +* Connection.CELL_4G +* Connection.CELL +* Connection.NONE + +## connection.type + +Это свойство предоставляет быстрый способ для определения состояния подключения устройства к сети и тип этого подключения. + +### Краткий пример + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### Изменения в API + +До Cordova 2.3.0 объект `Connection` был доступен через `navigator.network.connection`, после чего это свойство было изменено на `navigator.connection` в соответствии со спецификацией консорциума W3C. Он все еще доступен в его исходном расположении, но это расположение является устаревшим и в конечном итоге будет удалено. + +### Особенности iOS + +* iOS не может определить тип подключения к сотовой сети. + * `navigator.connection.type` имеет значение `Connection.CELL` для всех сотовых данных. + +### Особенности Windows Phone + +* Когда работает в эмуляторе, тип подключения всегда определяется `navigator.connection.type` как `Connection.UNKNOWN`. + +* Windows Phone не может определить тип подключения к сотовой сети. + + * `navigator.connection.type` имеет значение `Connection.CELL` для всех сотовых данных. + +### Особенности Tizen + +* Tizen может обнаружить только соединения Wi-Fi или наличие сотовой связи. + * `navigator.connection.type` имеет значение `Connection.CELL_2G` для всех сотовых данных. + +### Особенности Firefox OS + +* Firefox OS не может определить тип подключения к сотовой сети. + * `navigator.connection.type` имеет значение `Connection.CELL` для всех сотовых данных. + +# События, связанные с сетью + +## offline + +Событие возникает, когда приложение переходит в автономный режим, и устройство не подключено к сети Интернет. + + document.addEventListener("offline", yourCallbackFunction, false); + + +### Подробности + +Событие `offline` возникает, когда ранее подключенное устройство теряет подключение к сети, так что приложение больше не может получить доступ к Интернет. Он опирается на ту же информацию, что и Connection API и срабатывает, когда значение `connection.type` становится равным `NONE`. + +Приложения обычно должно использовать `window.addEventListener` чтобы добавить обработчик события после того как произойдет событие `deviceready`. + +### Краткий пример + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### Особенности iOS + +Во время первоначального запуска первому событию offline (если применимо) требуется по крайней мере секунду на срабатывание. + +### Особенности Windows Phone 7 + +Когда работает в эмуляторе, `connection.status` всегда неизвестен, так что это событие *не* срабатывает. + +### Особенности Windows Phone 8 + +Эмулятор сообщает тип подключения как `Cellular` , которое не меняется, поэтому событие не *не* срабатывает. + +## online + +Это событие возникает, когда приложение выходит в онлайн, и устройство подключается к Интернету. + + document.addEventListener("online", yourCallbackFunction, false); + + +### Подробности + +Событие `online` возникает, когда ранее не подключенное к сети устройство получает сетевое подключение, разрешающее приложению доступ к Интернету. Оно опирается на ту же информацию, Connection API и вызывается когда `connection.type` меняется с `NONE` в любое другое значение. + +Приложения обычно должны использовать `window.addEventListener` чтобы добавить обработчик события после того как произойдет событие `deviceready`. + +### Краткий пример + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### Особенности iOS + +Во время первоначального запуска первое событие `online` (если применимо) занимает по меньшей мере секунду на срабатывание, до этого момента `connection.type` является равным `UNKNOWN`. + +### Особенности Windows Phone 7 + +Когда работает в эмуляторе, `connection.status` всегда неизвестен, так что это событие *не* срабатывает. + +### Особенности Windows Phone 8 + +Эмулятор сообщает тип подключения как `Cellular` , которое не меняется, поэтому событие не *не* срабатывает. diff --git a/plugins/cordova-plugin-network-information/doc/zh/README.md b/plugins/cordova-plugin-network-information/doc/zh/README.md new file mode 100644 index 0000000..09e11e7 --- /dev/null +++ b/plugins/cordova-plugin-network-information/doc/zh/README.md @@ -0,0 +1,190 @@ + + +# cordova-plugin-network-information + +[![Build Status](https://travis-ci.org/apache/cordova-plugin-network-information.svg)](https://travis-ci.org/apache/cordova-plugin-network-information) + +這個外掛程式提供的舊版本的[網路資訊 API](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/)實現的。 它提供了有關該設備的行動電話和無線網路連接的資訊和設備是否已連接到 internet。 + +## 安裝 + + cordova plugin add cordova-plugin-network-information + + +## 支援的平臺 + + * 亞馬遜火 OS + * Android 系統 + * 黑莓 10 + * 瀏覽器 + * iOS + * Windows Phone 7 和 8 + * Tizen + * Windows + * 火狐瀏覽器作業系統 + +# 連接 + +> `connection`物件,通過公開 `navigator.connection` ,提供了有關該設備的行動電話和無線網路連接的資訊。 + +## 屬性 + + * connection.type + +## 常量 + + * Connection.UNKNOWN + * Connection.ETHERNET + * Connection.WIFI + * Connection.CELL_2G + * Connection.CELL_3G + * Connection.CELL_4G + * Connection.CELL + * Connection.NONE + +## connection.type + +此屬性提供快速的方法來確定設備的網路連接狀態,和連線類型。 + +### 快速的示例 + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### API 更改 + +科爾多瓦 2.3.0,直到 `Connection` 物件的訪問通過 `navigator.network.connection` 後才改為其中, `navigator.connection` 以匹配的 W3C 規範。 它在其原始位置,是仍然可用,但已廢棄,最終將被刪除。 + +### iOS 的怪癖 + + * iOS 無法檢測到蜂窩網路連接的類型。 + * `navigator.connection.type`設置為 `Connection.CELL` 為所有蜂窩資料。 + +### Windows Phone 怪癖 + + * 當運行在模擬器中,總能檢測到 `navigator.connection.type` 作為`Connection.UNKNOWN`. + + * Windows Phone 不能檢測的蜂窩網路連接的類型。 + + * `navigator.connection.type`設置為 `Connection.CELL` 為所有蜂窩資料。 + +### Windows 的怪癖 + + * 當電話 8.1 在模擬器中運行,總能檢測到 `navigator.connection.type` 作為 `Connection.ETHERNET`. + +### Tizen 怪癖 + + * 泰只能檢測一個 WiFi 或細胞連接。 + * `navigator.connection.type` 是所有蜂窩資料設置為 `Connection.CELL_2G`。 + +### 火狐瀏覽器作業系統的怪癖 + + * 火狐瀏覽器作業系統無法檢測到蜂窩網路連接的類型。 + * `navigator.connection.type`設置為 `Connection.CELL` 為所有蜂窩資料。 + +### 瀏覽器的怪癖 + + * 瀏覽器無法檢測到網路連接的類型。 `navigator.connection.type`總是被設置為`Connection.UNKNOWN`時線上。 + +# 與網路相關的事件 + +## offline + +當一個應用程式離線時,與該設備未連接到互聯網時,將觸發該事件。 + + document.addEventListener("offline", yourCallbackFunction, false); + + +### 詳細資訊 + +`offline`以前連接的設備失去網路連接,這樣,應用程式不再可以訪問互聯網時激發的事件。 它依賴于連接 API,相同的資訊和火災時的值 `connection.type` 變得`NONE`. + +應用程式通常應使用 `document.addEventListener` 將一個事件攔截器附加一次 `deviceready` 事件火災。 + +### 快速的示例 + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### iOS 的怪癖 + +在初始啟動期間,第一次離線事件 (如果適用) 需至少一秒的火。 + +### Windows Phone 7 的怪癖 + +當運行在模擬器中, `connection.status` 始終是未知的因此此事件不會*不*火。 + +### Windows Phone 8 怪癖 + +模擬程式報告連線類型為 `Cellular` ,而不會更改,所以該事件不會*不*火。 + +## online + +當應用程式進入線上狀態,和該設備將成為連接到互聯網時觸發此事件。 + + document.addEventListener("online", yourCallbackFunction, false); + + +### 詳細資訊 + +`online`當先前連接的行動裝置接收到一個網路連接以允許應用程式訪問互聯網時激發的事件。 它依賴于連接 API,相同的資訊,則會激發 `connection.type` 從更改 `NONE` 為任何其他值。 + +應用程式通常應使用 `document.addEventListener` 將一個事件攔截器附加一次 `deviceready` 事件火災。 + +### 快速的示例 + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### iOS 的怪癖 + +在初始啟動期間第一次 `online` 事件 (如果適用),至少需一秒的火災之前的, `connection.type` 是`UNKNOWN`. + +### Windows Phone 7 的怪癖 + +當運行在模擬器中, `connection.status` 始終是未知的因此此事件不會*不*火。 + +### Windows Phone 8 怪癖 + +模擬程式報告連線類型為 `Cellular` ,而不會更改,所以事件不**火。 \ No newline at end of file diff --git a/plugins/cordova-plugin-network-information/doc/zh/index.md b/plugins/cordova-plugin-network-information/doc/zh/index.md new file mode 100644 index 0000000..2041467 --- /dev/null +++ b/plugins/cordova-plugin-network-information/doc/zh/index.md @@ -0,0 +1,186 @@ + + +# cordova-plugin-network-information + +這個外掛程式提供的舊版本的[網路資訊 API][1]實現的。 它提供了有關該設備的行動電話和無線網路連接的資訊和設備是否已連接到 internet。 + + [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ + +## 安裝 + + cordova plugin add cordova-plugin-network-information + + +## 支援的平臺 + +* 亞馬遜火 OS +* Android 系統 +* 黑莓 10 +* 瀏覽器 +* iOS +* Windows Phone 7 和 8 +* 泰 +* Windows +* 火狐瀏覽器的作業系統 + +# 連接 + +> `connection`物件,通過公開 `navigator.connection` ,提供了有關該設備的行動電話和無線網路連接的資訊。 + +## 屬性 + +* connection.type + +## 常量 + +* Connection.UNKNOWN +* Connection.ETHERNET +* Connection.WIFI +* Connection.CELL_2G +* Connection.CELL_3G +* Connection.CELL_4G +* Connection.CELL +* Connection.NONE + +## connection.type + +此屬性提供快速的方法來確定設備的網路連接狀態,和連線類型。 + +### 快速的示例 + + function checkConnection() { + var networkState = navigator.connection.type; + + var states = {}; + states[Connection.UNKNOWN] = 'Unknown connection'; + states[Connection.ETHERNET] = 'Ethernet connection'; + states[Connection.WIFI] = 'WiFi connection'; + states[Connection.CELL_2G] = 'Cell 2G connection'; + states[Connection.CELL_3G] = 'Cell 3G connection'; + states[Connection.CELL_4G] = 'Cell 4G connection'; + states[Connection.CELL] = 'Cell generic connection'; + states[Connection.NONE] = 'No network connection'; + + alert('Connection type: ' + states[networkState]); + } + + checkConnection(); + + +### API 更改 + +科爾多瓦 2.3.0,直到 `Connection` 物件的訪問通過 `navigator.network.connection` 後才改為其中, `navigator.connection` 以匹配的 W3C 規範。 它在其原始位置,是仍然可用,但已廢棄,最終將被刪除。 + +### iOS 的怪癖 + +* iOS 無法檢測到蜂窩網路連接的類型。 + * `navigator.connection.type`設置為 `Connection.CELL` 為所有蜂窩資料。 + +### Windows Phone 怪癖 + +* 當運行在模擬器中,總能檢測到 `navigator.connection.type` 作為`Connection.UNKNOWN`. + +* Windows Phone 不能檢測的蜂窩網路連接的類型。 + + * `navigator.connection.type`設置為 `Connection.CELL` 為所有蜂窩資料。 + +### Windows 的怪癖 + +* 當電話 8.1 在模擬器中運行,總能檢測到 `navigator.connection.type` 作為 `Connection.ETHERNET`. + +### Tizen 怪癖 + +* 泰只能檢測一個 WiFi 或細胞連接。 + * `navigator.connection.type` 是所有蜂窩資料設置為 `Connection.CELL_2G`。 + +### 火狐瀏覽器作業系統的怪癖 + +* 火狐瀏覽器作業系統無法檢測到蜂窩網路連接的類型。 + * `navigator.connection.type`設置為 `Connection.CELL` 為所有蜂窩資料。 + +# 與網路相關的事件 + +## offline + +當一個應用程式離線時,與該設備未連接到互聯網時,將觸發該事件。 + + document.addEventListener("offline", yourCallbackFunction, false); + + +### 詳細資訊 + +`offline`以前連接的設備失去網路連接,這樣,應用程式不再可以訪問互聯網時激發的事件。 它依賴于連接 API,相同的資訊和火災時的值 `connection.type` 變得`NONE`. + +應用程式通常應使用 `document.addEventListener` 將一個事件攔截器附加一次 `deviceready` 事件火災。 + +### 快速的示例 + + document.addEventListener("offline", onOffline, false); + + function onOffline() { + // Handle the offline event + } + + +### iOS 的怪癖 + +在初始啟動期間,第一次離線事件 (如果適用) 需至少一秒的火。 + +### Windows Phone 7 的怪癖 + +當運行在模擬器中, `connection.status` 始終是未知的因此此事件不會*不*火。 + +### Windows Phone 8 怪癖 + +模擬程式報告連線類型為 `Cellular` ,而不會更改,所以該事件不會*不*火。 + +## online + +當應用程式進入線上狀態,和該設備將成為連接到互聯網時觸發此事件。 + + document.addEventListener("online", yourCallbackFunction, false); + + +### 詳細資訊 + +`online`當先前連接的行動裝置接收到一個網路連接以允許應用程式訪問互聯網時激發的事件。 它依賴于連接 API,相同的資訊,則會激發 `connection.type` 從更改 `NONE` 為任何其他值。 + +應用程式通常應使用 `document.addEventListener` 將一個事件攔截器附加一次 `deviceready` 事件火災。 + +### 快速的示例 + + document.addEventListener("online", onOnline, false); + + function onOnline() { + // Handle the online event + } + + +### iOS 的怪癖 + +在初始啟動期間第一次 `online` 事件 (如果適用),至少需一秒的火災之前的, `connection.type` 是`UNKNOWN`. + +### Windows Phone 7 的怪癖 + +當運行在模擬器中, `connection.status` 始終是未知的因此此事件不會*不*火。 + +### Windows Phone 8 怪癖 + +模擬程式報告連線類型為 `Cellular` ,而不會更改,所以事件不**火。 diff --git a/plugins/cordova-plugin-network-information/package.json b/plugins/cordova-plugin-network-information/package.json new file mode 100644 index 0000000..a9378f8 --- /dev/null +++ b/plugins/cordova-plugin-network-information/package.json @@ -0,0 +1,148 @@ +{ + "_args": [ + [ + { + "raw": "cordova-plugin-network-information@1", + "scope": null, + "escapedName": "cordova-plugin-network-information", + "name": "cordova-plugin-network-information", + "rawSpec": "1", + "spec": ">=1.0.0 <2.0.0", + "type": "range" + }, + "D:\\pWork\\yunkong2.vis.cordova\\node_modules" + ] + ], + "_from": "cordova-plugin-network-information@>=1.0.0 <2.0.0", + "_id": "cordova-plugin-network-information@1.3.3", + "_inCache": true, + "_location": "/cordova-plugin-network-information", + "_nodeVersion": "6.10.1", + "_npmOperationalInternal": { + "host": "packages-12-west.internal.npmjs.com", + "tmp": "tmp/cordova-plugin-network-information-1.3.3.tgz_1493685649926_0.8318859627470374" + }, + "_npmUser": { + "name": "filmaj", + "email": "maj.fil@gmail.com" + }, + "_npmVersion": "3.10.10", + "_phantomChildren": {}, + "_requested": { + "raw": "cordova-plugin-network-information@1", + "scope": null, + "escapedName": "cordova-plugin-network-information", + "name": "cordova-plugin-network-information", + "rawSpec": "1", + "spec": ">=1.0.0 <2.0.0", + "type": "range" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "https://registry.npmjs.org/cordova-plugin-network-information/-/cordova-plugin-network-information-1.3.3.tgz", + "_shasum": "0ea9aa5c1124cf7cbd6f84f828a542cbd24a8518", + "_shrinkwrap": null, + "_spec": "cordova-plugin-network-information@1", + "_where": "D:\\pWork\\yunkong2.vis.cordova\\node_modules", + "author": { + "name": "Apache Software Foundation" + }, + "bugs": { + "url": "https://github.com/apache/cordova-plugin-network-information/issues" + }, + "cordova": { + "id": "cordova-plugin-network-information", + "platforms": [ + "firefoxos", + "android", + "amazon-fireos", + "ubuntu", + "ios", + "blackberry10", + "wp7", + "wp8", + "windows8", + "windows", + "tizen", + "browser" + ] + }, + "dependencies": {}, + "description": "Cordova Network Information Plugin", + "devDependencies": { + "jshint": "^2.6.0" + }, + "directories": {}, + "dist": { + "shasum": "0ea9aa5c1124cf7cbd6f84f828a542cbd24a8518", + "tarball": "https://registry.npmjs.org/cordova-plugin-network-information/-/cordova-plugin-network-information-1.3.3.tgz" + }, + "engines": { + "cordovaDependencies": { + "2.0.0": { + "cordova": ">100" + } + } + }, + "homepage": "https://github.com/apache/cordova-plugin-network-information#readme", + "keywords": [ + "cordova", + "network", + "information", + "ecosystem:cordova", + "cordova-firefoxos", + "cordova-android", + "cordova-amazon-fireos", + "cordova-ubuntu", + "cordova-ios", + "cordova-blackberry10", + "cordova-wp7", + "cordova-wp8", + "cordova-windows8", + "cordova-windows", + "cordova-tizen", + "cordova-browser" + ], + "license": "Apache-2.0", + "maintainers": [ + { + "name": "bowserj", + "email": "bowserj@apache.org" + }, + { + "name": "csantanapr", + "email": "csantana23@gmail.com" + }, + { + "name": "filmaj", + "email": "maj.fil@gmail.com" + }, + { + "name": "purplecabbage", + "email": "purplecabbage@gmail.com" + }, + { + "name": "shazron", + "email": "shazron@gmail.com" + }, + { + "name": "stevegill", + "email": "stevengill97@gmail.com" + } + ], + "name": "cordova-plugin-network-information", + "optionalDependencies": {}, + "readme": "ERROR: No README data found!", + "repository": { + "type": "git", + "url": "git+https://github.com/apache/cordova-plugin-network-information.git" + }, + "scripts": { + "jshint": "jshint www && jshint src && jshint tests", + "test": "npm run jshint" + }, + "types": "./types/index.d.ts", + "version": "1.3.3" +} diff --git a/plugins/cordova-plugin-network-information/plugin.xml b/plugins/cordova-plugin-network-information/plugin.xml new file mode 100644 index 0000000..8b56f47 --- /dev/null +++ b/plugins/cordova-plugin-network-information/plugin.xml @@ -0,0 +1,174 @@ + + + + + + Network Information + Cordova Network Information Plugin + Apache 2.0 + cordova,network,information + https://git-wip-us.apache.org/repos/asf/cordova-plugin-network-information.git + https://issues.apache.org/jira/browse/CB/component/12320640 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/cordova-plugin-network-information/src/android/NetworkManager.java b/plugins/cordova-plugin-network-information/src/android/NetworkManager.java new file mode 100644 index 0000000..614b6e7 --- /dev/null +++ b/plugins/cordova-plugin-network-information/src/android/NetworkManager.java @@ -0,0 +1,287 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ +package org.apache.cordova.networkinformation; + +import org.apache.cordova.CallbackContext; +import org.apache.cordova.CordovaInterface; +import org.apache.cordova.CordovaPlugin; +import org.apache.cordova.LOG; +import org.apache.cordova.PluginResult; +import org.apache.cordova.CordovaWebView; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; + +import java.util.Locale; + +public class NetworkManager extends CordovaPlugin { + + public static int NOT_REACHABLE = 0; + public static int REACHABLE_VIA_CARRIER_DATA_NETWORK = 1; + public static int REACHABLE_VIA_WIFI_NETWORK = 2; + + public static final String WIFI = "wifi"; + public static final String WIMAX = "wimax"; + // mobile + public static final String MOBILE = "mobile"; + + // Android L calls this Cellular, because I have no idea! + public static final String CELLULAR = "cellular"; + // 2G network types + public static final String TWO_G = "2g"; + public static final String GSM = "gsm"; + public static final String GPRS = "gprs"; + public static final String EDGE = "edge"; + // 3G network types + public static final String THREE_G = "3g"; + public static final String CDMA = "cdma"; + public static final String UMTS = "umts"; + public static final String HSPA = "hspa"; + public static final String HSUPA = "hsupa"; + public static final String HSDPA = "hsdpa"; + public static final String ONEXRTT = "1xrtt"; + public static final String EHRPD = "ehrpd"; + // 4G network types + public static final String FOUR_G = "4g"; + public static final String LTE = "lte"; + public static final String UMB = "umb"; + public static final String HSPA_PLUS = "hspa+"; + // return type + public static final String TYPE_UNKNOWN = "unknown"; + public static final String TYPE_ETHERNET = "ethernet"; + public static final String TYPE_ETHERNET_SHORT = "eth"; + public static final String TYPE_WIFI = "wifi"; + public static final String TYPE_2G = "2g"; + public static final String TYPE_3G = "3g"; + public static final String TYPE_4G = "4g"; + public static final String TYPE_NONE = "none"; + + private static final String LOG_TAG = "NetworkManager"; + + private CallbackContext connectionCallbackContext; + + ConnectivityManager sockMan; + BroadcastReceiver receiver; + private JSONObject lastInfo = null; + + /** + * Sets the context of the Command. This can then be used to do things like + * get file paths associated with the Activity. + * + * @param cordova The context of the main Activity. + * @param webView The CordovaWebView Cordova is running in. + */ + public void initialize(CordovaInterface cordova, CordovaWebView webView) { + super.initialize(cordova, webView); + this.sockMan = (ConnectivityManager) cordova.getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); + this.connectionCallbackContext = null; + + // We need to listen to connectivity events to update navigator.connection + IntentFilter intentFilter = new IntentFilter(); + intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); + if (this.receiver == null) { + this.receiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + // (The null check is for the ARM Emulator, please use Intel Emulator for better results) + if(NetworkManager.this.webView != null) + updateConnectionInfo(sockMan.getActiveNetworkInfo()); + } + }; + webView.getContext().registerReceiver(this.receiver, intentFilter); + } + + } + + /** + * Executes the request and returns PluginResult. + * + * @param action The action to execute. + * @param args JSONArry of arguments for the plugin. + * @param callbackContext The callback id used when calling back into JavaScript. + * @return True if the action was valid, false otherwise. + */ + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { + if (action.equals("getConnectionInfo")) { + this.connectionCallbackContext = callbackContext; + NetworkInfo info = sockMan.getActiveNetworkInfo(); + String connectionType = ""; + try { + connectionType = this.getConnectionInfo(info).get("type").toString(); + } catch (JSONException e) { + LOG.d(LOG_TAG, e.getLocalizedMessage()); + } + + PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, connectionType); + pluginResult.setKeepCallback(true); + callbackContext.sendPluginResult(pluginResult); + return true; + } + return false; + } + + /** + * Stop network receiver. + */ + public void onDestroy() { + if (this.receiver != null) { + try { + webView.getContext().unregisterReceiver(this.receiver); + } catch (Exception e) { + LOG.e(LOG_TAG, "Error unregistering network receiver: " + e.getMessage(), e); + } finally { + receiver = null; + } + } + } + + //-------------------------------------------------------------------------- + // LOCAL METHODS + //-------------------------------------------------------------------------- + + /** + * Updates the JavaScript side whenever the connection changes + * + * @param info the current active network info + * @return + */ + private void updateConnectionInfo(NetworkInfo info) { + // send update to javascript "navigator.network.connection" + // Jellybean sends its own info + JSONObject thisInfo = this.getConnectionInfo(info); + if(!thisInfo.equals(lastInfo)) + { + String connectionType = ""; + try { + connectionType = thisInfo.get("type").toString(); + } catch (JSONException e) { + LOG.d(LOG_TAG, e.getLocalizedMessage()); + } + + sendUpdate(connectionType); + lastInfo = thisInfo; + } + } + + /** + * Get the latest network connection information + * + * @param info the current active network info + * @return a JSONObject that represents the network info + */ + private JSONObject getConnectionInfo(NetworkInfo info) { + String type = TYPE_NONE; + String extraInfo = ""; + if (info != null) { + // If we are not connected to any network set type to none + if (!info.isConnected()) { + type = TYPE_NONE; + } + else { + type = getType(info); + } + extraInfo = info.getExtraInfo(); + } + + LOG.d(LOG_TAG, "Connection Type: " + type); + LOG.d(LOG_TAG, "Connection Extra Info: " + extraInfo); + + JSONObject connectionInfo = new JSONObject(); + + try { + connectionInfo.put("type", type); + connectionInfo.put("extraInfo", extraInfo); + } catch (JSONException e) { + LOG.d(LOG_TAG, e.getLocalizedMessage()); + } + + return connectionInfo; + } + + /** + * Create a new plugin result and send it back to JavaScript + * + * @param connection the network info to set as navigator.connection + */ + private void sendUpdate(String type) { + if (connectionCallbackContext != null) { + PluginResult result = new PluginResult(PluginResult.Status.OK, type); + result.setKeepCallback(true); + connectionCallbackContext.sendPluginResult(result); + } + webView.postMessage("networkconnection", type); + } + + /** + * Determine the type of connection + * + * @param info the network info so we can determine connection type. + * @return the type of mobile network we are on + */ + private String getType(NetworkInfo info) { + if (info != null) { + String type = info.getTypeName().toLowerCase(Locale.US); + + LOG.d(LOG_TAG, "toLower : " + type.toLowerCase()); + LOG.d(LOG_TAG, "wifi : " + WIFI); + if (type.equals(WIFI)) { + return TYPE_WIFI; + } + else if (type.toLowerCase().equals(TYPE_ETHERNET) || type.toLowerCase().startsWith(TYPE_ETHERNET_SHORT)) { + return TYPE_ETHERNET; + } + else if (type.equals(MOBILE) || type.equals(CELLULAR)) { + type = info.getSubtypeName().toLowerCase(Locale.US); + if (type.equals(GSM) || + type.equals(GPRS) || + type.equals(EDGE) || + type.equals(TWO_G)) { + return TYPE_2G; + } + else if (type.startsWith(CDMA) || + type.equals(UMTS) || + type.equals(ONEXRTT) || + type.equals(EHRPD) || + type.equals(HSUPA) || + type.equals(HSDPA) || + type.equals(HSPA) || + type.equals(THREE_G)) { + return TYPE_3G; + } + else if (type.equals(LTE) || + type.equals(UMB) || + type.equals(HSPA_PLUS) || + type.equals(FOUR_G)) { + return TYPE_4G; + } + } + } + else { + return TYPE_NONE; + } + return TYPE_UNKNOWN; + } +} diff --git a/plugins/cordova-plugin-network-information/src/blackberry10/index.js b/plugins/cordova-plugin-network-information/src/blackberry10/index.js new file mode 100644 index 0000000..c6cd00a --- /dev/null +++ b/plugins/cordova-plugin-network-information/src/blackberry10/index.js @@ -0,0 +1,66 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +/* global PluginResult */ + +//map from BB10 to cordova connection types: +//https://github.com/apache/cordova-js/blob/master/lib/common/plugin/Connection.js +function mapConnectionType(con) { + switch (con.type) { + case 'wired': + return 'ethernet'; + case 'wifi': + return 'wifi'; + case 'none': + return 'none'; + case 'cellular': + switch (con.technology) { + case 'edge': + case 'gsm': + return '2g'; + case 'evdo': + return '3g'; + case 'umts': + return '3g'; + case 'lte': + return '4g'; + } + return "cellular"; + } + return 'unknown'; +} + +function currentConnectionType() { + try { + //possible for webplatform to throw pps exception + return mapConnectionType(window.qnx.webplatform.device.activeConnection || { type : 'none' }); + } + catch (e) { + return 'unknown'; + } +} + +module.exports = { + getConnectionInfo: function (success, fail, args, env) { + var result = new PluginResult(args, env); + result.ok(currentConnectionType()); + } +}; diff --git a/plugins/cordova-plugin-network-information/src/browser/network.js b/plugins/cordova-plugin-network-information/src/browser/network.js new file mode 100644 index 0000000..8a6ddb0 --- /dev/null +++ b/plugins/cordova-plugin-network-information/src/browser/network.js @@ -0,0 +1,48 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +var cordova = require('cordova'), + proxy = require("cordova/exec/proxy"), + Connection = require('./Connection'); + +var type = navigator.onLine ? Connection.UNKNOWN : Connection.NONE; + +// Subscribe to 'native' online/offline events +function onStatusChange(evt) { + type = navigator.onLine ? Connection.UNKNOWN : Connection.NONE; + // force async + setTimeout(function(){ + cordova.fireDocumentEvent(evt.type); + },0); +} + +window.addEventListener('online', onStatusChange); +window.addEventListener('offline', onStatusChange); + +proxy.add("NetworkStatus", { + getConnectionInfo:function(cbSuccess) { + // force async + setTimeout(function(){ + cbSuccess(type); + },0); + } +}); + + diff --git a/plugins/cordova-plugin-network-information/src/firefoxos/NetworkProxy.js b/plugins/cordova-plugin-network-information/src/firefoxos/NetworkProxy.js new file mode 100644 index 0000000..8c82557 --- /dev/null +++ b/plugins/cordova-plugin-network-information/src/firefoxos/NetworkProxy.js @@ -0,0 +1,96 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +/* + Network API overview: http://www.w3.org/TR/netinfo-api/ + and http://w3c.github.io/netinfo/ +*/ + +var Connection = require('./Connection'), + modulemapper = require('cordova/modulemapper'); + +var origConnection = modulemapper.getOriginalSymbol(window, 'navigator.connection'); + +module.exports = { + + getConnectionInfo: function(successCallback, errorCallback) { + var connection = origConnection || navigator.mozConnection, + connectionType = Connection.UNKNOWN; + + if (!connection) { + setTimeout(function() { + successCallback(connectionType); + }, 0); + return; + } + + var bandwidth = connection.bandwidth, + metered = connection.metered, + type = connection.type; + + if (type !== undefined) { + // For more information see: + // https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API + + switch(type) { + case "cellular": + connectionType = Connection.CELL; + break; + case "ethernet": + connectionType = Connection.ETHERNET; + break; + case "wifi": + connectionType = Connection.WIFI; + break; + case "none": + connectionType = Connection.NONE; + break; + } + } else if (bandwidth !== undefined && metered !== undefined) { + /* + bandwidth of type double, readonly + The user agent must set the value of the bandwidth attribute to: + 0 if the user is currently offline; + Infinity if the bandwidth is unknown; + an estimation of the current bandwidth in MB/s (Megabytes per seconds) + available for communication with the browsing context active document's + domain. + + For more information see: + https://developer.mozilla.org/en-US/docs/Web/API/Connection + */ + + if (bandwidth === 0) { + connectionType = Connection.NONE; + } else if (metered && isFinite(bandwidth)) { + connectionType = Connection.CELL; + } else if (!metered && isFinite(bandwidth)) { + connectionType = Connection.WIFI; + } + } + + setTimeout(function() { + successCallback(connectionType); + }, 0); + } +}; + +require("cordova/exec/proxy").add("NetworkStatus", module.exports); diff --git a/plugins/cordova-plugin-network-information/src/ios/CDVConnection.h b/plugins/cordova-plugin-network-information/src/ios/CDVConnection.h new file mode 100644 index 0000000..8add027 --- /dev/null +++ b/plugins/cordova-plugin-network-information/src/ios/CDVConnection.h @@ -0,0 +1,34 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ + +#import +#import +#import "CDVReachability.h" + +@interface CDVConnection : CDVPlugin { + NSString* type; + NSString* _callbackId; + + CDVReachability* internetReach; +} + +@property (copy) NSString* connectionType; +@property (strong) CDVReachability* internetReach; + +@end diff --git a/plugins/cordova-plugin-network-information/src/ios/CDVConnection.m b/plugins/cordova-plugin-network-information/src/ios/CDVConnection.m new file mode 100644 index 0000000..6715322 --- /dev/null +++ b/plugins/cordova-plugin-network-information/src/ios/CDVConnection.m @@ -0,0 +1,156 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ +#import + +#import "CDVConnection.h" +#import "CDVReachability.h" + +@interface CDVConnection (PrivateMethods) +- (void)updateOnlineStatus; +- (void)sendPluginResult; +@end + +@implementation CDVConnection + +@synthesize connectionType, internetReach; + +- (void)getConnectionInfo:(CDVInvokedUrlCommand*)command +{ + _callbackId = command.callbackId; + [self sendPluginResult]; +} + +- (void)sendPluginResult +{ + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:self.connectionType]; + + [result setKeepCallbackAsBool:YES]; + [self.commandDelegate sendPluginResult:result callbackId:_callbackId]; +} + +- (NSString*)w3cConnectionTypeFor:(CDVReachability*)reachability +{ + NetworkStatus networkStatus = [reachability currentReachabilityStatus]; + + switch (networkStatus) { + case NotReachable: + return @"none"; + + case ReachableViaWWAN: + { + BOOL isConnectionRequired = [reachability connectionRequired]; + if (isConnectionRequired) { + return @"none"; + } else { + if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0" options:NSNumericSearch] != NSOrderedAscending) { + CTTelephonyNetworkInfo *telephonyInfo = [CTTelephonyNetworkInfo new]; + if ([telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyGPRS]) { + return @"2g"; + } else if ([telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyEdge]) { + return @"2g"; + } else if ([telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyWCDMA]) { + return @"3g"; + } else if ([telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyHSDPA]) { + return @"3g"; + } else if ([telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyHSUPA]) { + return @"3g"; + } else if ([telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMA1x]) { + return @"3g"; + } else if ([telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORev0]) { + return @"3g"; + } else if ([telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORevA]) { + return @"3g"; + } else if ([telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORevB]) { + return @"3g"; + } else if ([telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyeHRPD]) { + return @"3g"; + } else if ([telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyLTE]) { + return @"4g"; + } + } + return @"cellular"; + } + } + case ReachableViaWiFi: + return @"wifi"; + + default: + return @"unknown"; + } +} + +- (BOOL)isCellularConnection:(NSString*)theConnectionType +{ + return [theConnectionType isEqualToString:@"2g"] || + [theConnectionType isEqualToString:@"3g"] || + [theConnectionType isEqualToString:@"4g"] || + [theConnectionType isEqualToString:@"cellular"]; +} + +- (void)updateReachability:(CDVReachability*)reachability +{ + if (reachability) { + // check whether the connection type has changed + NSString* newConnectionType = [self w3cConnectionTypeFor:reachability]; + if ([newConnectionType isEqualToString:self.connectionType]) { // the same as before, remove dupes + return; + } else { + self.connectionType = [self w3cConnectionTypeFor:reachability]; + } + } + [self sendPluginResult]; +} + +- (void)updateConnectionType:(NSNotification*)note +{ + CDVReachability* curReach = [note object]; + + if ((curReach != nil) && [curReach isKindOfClass:[CDVReachability class]]) { + [self updateReachability:curReach]; + } +} + +- (void)onPause +{ + [self.internetReach stopNotifier]; +} + +- (void)onResume +{ + [self.internetReach startNotifier]; + [self updateReachability:self.internetReach]; +} + +- (void)pluginInitialize +{ + self.connectionType = @"none"; + self.internetReach = [CDVReachability reachabilityForInternetConnection]; + self.connectionType = [self w3cConnectionTypeFor:self.internetReach]; + [self.internetReach startNotifier]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateConnectionType:) + name:kReachabilityChangedNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateConnectionType:) + name:CTRadioAccessTechnologyDidChangeNotification object:nil]; + if (UIApplicationDidEnterBackgroundNotification && UIApplicationWillEnterForegroundNotification) { + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onPause) name:UIApplicationDidEnterBackgroundNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onResume) name:UIApplicationWillEnterForegroundNotification object:nil]; + } +} + +@end diff --git a/plugins/cordova-plugin-network-information/src/ios/CDVReachability.h b/plugins/cordova-plugin-network-information/src/ios/CDVReachability.h new file mode 100644 index 0000000..852d37b --- /dev/null +++ b/plugins/cordova-plugin-network-information/src/ios/CDVReachability.h @@ -0,0 +1,81 @@ +/* + + File: Reachability.h + Abstract: Basic demonstration of how to use the SystemConfiguration Reachability APIs. + Version: 2.2 + + Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. + ("Apple") in consideration of your agreement to the following terms, and your + use, installation, modification or redistribution of this Apple software + constitutes acceptance of these terms. If you do not agree with these terms, + please do not use, install, modify or redistribute this Apple software. + + In consideration of your agreement to abide by the following terms, and subject + to these terms, Apple grants you a personal, non-exclusive license, under + Apple's copyrights in this original Apple software (the "Apple Software"), to + use, reproduce, modify and redistribute the Apple Software, with or without + modifications, in source and/or binary forms; provided that if you redistribute + the Apple Software in its entirety and without modifications, you must retain + this notice and the following text and disclaimers in all such redistributions + of the Apple Software. + Neither the name, trademarks, service marks or logos of Apple Inc. may be used + to endorse or promote products derived from the Apple Software without specific + prior written permission from Apple. Except as expressly stated in this notice, + no other rights or licenses, express or implied, are granted by Apple herein, + including but not limited to any patent rights that may be infringed by your + derivative works or by other works in which the Apple Software may be + incorporated. + + The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED + WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN + COMBINATION WITH YOUR PRODUCTS. + + IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR + DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF + CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF + APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + Copyright (C) 2010 Apple Inc. All Rights Reserved. + +*/ + +#import +#import +#import + +typedef enum { + NotReachable = 0, + ReachableViaWWAN, // this value has been swapped with ReachableViaWiFi for Cordova backwards compat. reasons + ReachableViaWiFi // this value has been swapped with ReachableViaWWAN for Cordova backwards compat. reasons +} NetworkStatus; +#define kReachabilityChangedNotification @"kNetworkReachabilityChangedNotification" + +@interface CDVReachability : NSObject +{ + SCNetworkReachabilityRef reachabilityRef; +} + +// reachabilityWithHostName- Use to check the reachability of a particular host name. ++ (CDVReachability*)reachabilityWithHostName:(NSString*)hostName; + +// reachabilityWithAddress- Use to check the reachability of a particular IP address. ++ (CDVReachability*)reachabilityWithAddress:(const struct sockaddr*)hostAddress; + +// reachabilityForInternetConnection- checks whether the default route is available. +// Should be used by applications that do not connect to a particular host ++ (CDVReachability*)reachabilityForInternetConnection; + +// Start listening for reachability notifications on the current run loop +- (BOOL)startNotifier; +- (void)stopNotifier; + +- (NetworkStatus)currentReachabilityStatus; +// WWAN may be available, but not active until a connection has been established. +// WiFi may require a connection for VPN on Demand. +- (BOOL)connectionRequired; +@end diff --git a/plugins/cordova-plugin-network-information/src/ios/CDVReachability.m b/plugins/cordova-plugin-network-information/src/ios/CDVReachability.m new file mode 100644 index 0000000..b43a62d --- /dev/null +++ b/plugins/cordova-plugin-network-information/src/ios/CDVReachability.m @@ -0,0 +1,237 @@ +/* + + File: Reachability.m + Abstract: Basic demonstration of how to use the SystemConfiguration Reachability APIs. + Version: 2.2 + + Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. + ("Apple") in consideration of your agreement to the following terms, and your + use, installation, modification or redistribution of this Apple software + constitutes acceptance of these terms. If you do not agree with these terms, + please do not use, install, modify or redistribute this Apple software. + + In consideration of your agreement to abide by the following terms, and subject + to these terms, Apple grants you a personal, non-exclusive license, under + Apple's copyrights in this original Apple software (the "Apple Software"), to + use, reproduce, modify and redistribute the Apple Software, with or without + modifications, in source and/or binary forms; provided that if you redistribute + the Apple Software in its entirety and without modifications, you must retain + this notice and the following text and disclaimers in all such redistributions + of the Apple Software. + Neither the name, trademarks, service marks or logos of Apple Inc. may be used + to endorse or promote products derived from the Apple Software without specific + prior written permission from Apple. Except as expressly stated in this notice, + no other rights or licenses, express or implied, are granted by Apple herein, + including but not limited to any patent rights that may be infringed by your + derivative works or by other works in which the Apple Software may be + incorporated. + + The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED + WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN + COMBINATION WITH YOUR PRODUCTS. + + IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR + DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF + CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF + APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + Copyright (C) 2010 Apple Inc. All Rights Reserved. + +*/ + +#import +#import +#import +#import +#import +#import + +#import + +#import "CDVReachability.h" + +#define kShouldPrintReachabilityFlags 0 + +static void CDVPrintReachabilityFlags(SCNetworkReachabilityFlags flags, const char* comment) +{ +#if kShouldPrintReachabilityFlags + NSLog(@"Reachability Flag Status: %c%c %c%c%c%c%c%c%c %s\n", + (flags & kSCNetworkReachabilityFlagsIsWWAN) ? 'W' : '-', + (flags & kSCNetworkReachabilityFlagsReachable) ? 'R' : '-', + + (flags & kSCNetworkReachabilityFlagsTransientConnection) ? 't' : '-', + (flags & kSCNetworkReachabilityFlagsConnectionRequired) ? 'c' : '-', + (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) ? 'C' : '-', + (flags & kSCNetworkReachabilityFlagsInterventionRequired) ? 'i' : '-', + (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) ? 'D' : '-', + (flags & kSCNetworkReachabilityFlagsIsLocalAddress) ? 'l' : '-', + (flags & kSCNetworkReachabilityFlagsIsDirect) ? 'd' : '-', + comment + ); +#endif +} + +@implementation CDVReachability + +static void CDVReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info) +{ +#pragma unused (target, flags) + // NSCAssert(info != NULL, @"info was NULL in ReachabilityCallback"); + // NSCAssert([(NSObject*) info isKindOfClass: [Reachability class]], @"info was wrong class in ReachabilityCallback"); + + // Converted the asserts above to conditionals, with safe return from the function + if (info == NULL) { + NSLog(@"info was NULL in ReachabilityCallback"); + return; + } + + if (![(__bridge NSObject*)info isKindOfClass :[CDVReachability class]]) { + NSLog(@"info was wrong class in ReachabilityCallback"); + return; + } + + // We're on the main RunLoop, so an NSAutoreleasePool is not necessary, but is added defensively + // in case someon uses the Reachability object in a different thread. + @autoreleasepool { + CDVReachability* noteObject = (__bridge CDVReachability*)info; + // Post a notification to notify the client that the network reachability changed. + [[NSNotificationCenter defaultCenter] postNotificationName:kReachabilityChangedNotification object:noteObject]; + } +} + +- (BOOL)startNotifier +{ + BOOL retVal = NO; + SCNetworkReachabilityContext context = {0, (__bridge void*)(self), NULL, NULL, NULL}; + + if (SCNetworkReachabilitySetCallback(reachabilityRef, CDVReachabilityCallback, &context)) { + if (SCNetworkReachabilityScheduleWithRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode)) { + retVal = YES; + } + } + return retVal; +} + +- (void)stopNotifier +{ + if (reachabilityRef != NULL) { + SCNetworkReachabilitySetCallback(reachabilityRef, NULL, NULL); + SCNetworkReachabilityUnscheduleFromRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); + } +} + +- (void)dealloc +{ + [self stopNotifier]; + if (reachabilityRef != NULL) { + CFRelease(reachabilityRef); + } +} + ++ (CDVReachability*)reachabilityWithHostName:(NSString*)hostName; +{ + CDVReachability* retVal = NULL; + SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, [hostName UTF8String]); + if (reachability != NULL) { + retVal = [[self alloc] init]; + if (retVal != NULL) { + retVal->reachabilityRef = reachability; + } + else { + CFRelease(reachability); + } + } + return retVal; +} + ++ (CDVReachability*)reachabilityWithAddress:(const struct sockaddr*)hostAddress; +{ + SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, hostAddress); + CDVReachability* retVal = NULL; + if (reachability != NULL) { + retVal = [[self alloc] init]; + if (retVal != NULL) { + retVal->reachabilityRef = reachability; + } + else { + CFRelease(reachability); + } + } + return retVal; +} + +// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing +// status of the device, both IPv4 and IPv6. ++ (CDVReachability*)reachabilityForInternetConnection; +{ + struct sockaddr_in zeroAddress; + bzero(&zeroAddress, sizeof(zeroAddress)); + zeroAddress.sin_len = sizeof(zeroAddress); + zeroAddress.sin_family = AF_INET; + return [self reachabilityWithAddress:(const struct sockaddr*) &zeroAddress]; +} + +#pragma mark Network Flag Handling + +- (NetworkStatus)networkStatusForFlags:(SCNetworkReachabilityFlags)flags +{ + CDVPrintReachabilityFlags(flags, "networkStatusForFlags"); + if ((flags & kSCNetworkReachabilityFlagsReachable) == 0) { + // if target host is not reachable + return NotReachable; + } + + NetworkStatus retVal = NotReachable; + + if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0) { + // if target host is reachable and no connection is required + // then we'll assume (for now) that your on Wi-Fi + retVal = ReachableViaWiFi; + } + + if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0) || + ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))) { + // ... and the connection is on-demand (or on-traffic) if the + // calling application is using the CFSocketStream or higher APIs + + if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0) { + // ... and no [user] intervention is needed + retVal = ReachableViaWiFi; + } + } + + if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN) { + // ... but WWAN connections are OK if the calling application + // is using the CFNetwork (CFSocketStream?) APIs. + retVal = ReachableViaWWAN; + } + return retVal; +} + +- (BOOL)connectionRequired; +{ + NSAssert(reachabilityRef != NULL, @"connectionRequired called with NULL reachabilityRef"); + SCNetworkReachabilityFlags flags; + if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags)) { + return flags & kSCNetworkReachabilityFlagsConnectionRequired; + } + return NO; +} + +- (NetworkStatus)currentReachabilityStatus +{ + NSAssert(reachabilityRef != NULL, @"currentNetworkStatus called with NULL reachabilityRef"); + NetworkStatus retVal = NotReachable; + SCNetworkReachabilityFlags flags; + if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags)) { + retVal = [self networkStatusForFlags:flags]; + } + return retVal; +} + +@end diff --git a/plugins/cordova-plugin-network-information/src/tizen/NetworkProxy.js b/plugins/cordova-plugin-network-information/src/tizen/NetworkProxy.js new file mode 100644 index 0000000..d2de2cc --- /dev/null +++ b/plugins/cordova-plugin-network-information/src/tizen/NetworkProxy.js @@ -0,0 +1,93 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +/* global tizen */ + +var Connection = require('./Connection'); + +module.exports = { + getConnectionInfo: function(successCallback, errorCallback) { + var cncType = Connection.NONE; + var infoCount = 0; + var deviceCapabilities = null; + var timerId = 0; + var timeout = 300; + + + function connectionCB() { + if (timerId !== null) { + clearTimeout(timerId); + timerId = null; + } + + infoCount++; + + if (infoCount > 1) { + if (successCallback) { + successCallback(cncType); + } + } + } + + function errorCB(error) { + console.log("Error: " + error.code + "," + error.name + "," + error.message); + + if (errorCallback) { + errorCallback(); + } + } + + function wifiSuccessCB(wifi) { + if ((wifi.status === "ON") && (wifi.ipAddress.length !== 0)) { + cncType = Connection.WIFI; + } + connectionCB(); + } + + function cellularSuccessCB(cell) { + if ((cncType === Connection.NONE) && (cell.status === "ON") && (cell.ipAddress.length !== 0)) { + cncType = Connection.CELL_2G; + } + connectionCB(); + } + + + deviceCapabilities = tizen.systeminfo.getCapabilities(); + + + timerId = setTimeout(function() { + timerId = null; + infoCount = 1; + connectionCB(); + }, timeout); + + + if (deviceCapabilities.wifi) { + tizen.systeminfo.getPropertyValue("WIFI_NETWORK", wifiSuccessCB, errorCB); + } + + if (deviceCapabilities.telephony) { + tizen.systeminfo.getPropertyValue("CELLULAR_NETWORK", cellularSuccessCB, errorCB); + } + } +}; + +require("cordova/tizen/commandProxy").add("NetworkStatus", module.exports); diff --git a/plugins/cordova-plugin-network-information/src/ubuntu/network_information.cpp b/plugins/cordova-plugin-network-information/src/ubuntu/network_information.cpp new file mode 100644 index 0000000..8fdb494 --- /dev/null +++ b/plugins/cordova-plugin-network-information/src/ubuntu/network_information.cpp @@ -0,0 +1,63 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "network_information.h" + +void NetworkInformation::getConnectionInfo(int scId, int ecId) { + Q_UNUSED(ecId); + + QString result; + QNetworkInfo::NetworkMode networkMode = m_systemNetworkInfo.currentNetworkMode(); + QNetworkInfo::NetworkStatus networkStatus = m_systemNetworkInfo.networkStatus(networkMode, 0); + QNetworkInfo::CellDataTechnology cellDataTechnology = m_systemNetworkInfo.currentCellDataTechnology(0); + + if (networkStatus == QNetworkInfo::NoNetworkAvailable) + result = "Connection.NONE"; + + switch (networkMode) { + case QNetworkInfo::WimaxMode: + case QNetworkInfo::WlanMode: + result = "Connection.WIFI"; + break; + case QNetworkInfo::EthernetMode: + result = "Connection.ETHERNET"; + break; + case QNetworkInfo::LteMode: + result = "Connection.CELL_4G"; + break; + case QNetworkInfo::GsmMode: + case QNetworkInfo::CdmaMode: + case QNetworkInfo::TdscdmaMode: + case QNetworkInfo::WcdmaMode: + switch (cellDataTechnology) { + case QNetworkInfo::UmtsDataTechnology: + case QNetworkInfo::HspaDataTechnology: + result = "Connection.CELL_3G"; + break; + case QNetworkInfo::EdgeDataTechnology: + case QNetworkInfo::GprsDataTechnology: + result = "Connection.CELL_2G"; + break; + case QNetworkInfo::UnknownDataTechnology: + result = "Connection.UNKNOWN"; + break; + } + case QNetworkInfo::BluetoothMode: + case QNetworkInfo::UnknownMode: + result = "Connection.UNKNOWN"; + break; + } + + this->callback(scId, result); +} diff --git a/plugins/cordova-plugin-network-information/src/ubuntu/network_information.h b/plugins/cordova-plugin-network-information/src/ubuntu/network_information.h new file mode 100644 index 0000000..aca20e7 --- /dev/null +++ b/plugins/cordova-plugin-network-information/src/ubuntu/network_information.h @@ -0,0 +1,47 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NETWORK_INFORMATION_H +#define NETWORK_INFORMATION_H + +#include + +#include +#include + +class NetworkInformation: public CPlugin { + Q_OBJECT +public: + explicit NetworkInformation(Cordova *cordova): CPlugin(cordova) {} + + virtual const QString fullName() override { + return NetworkInformation::fullID(); + } + + virtual const QString shortName() override { + return "Connection"; + } + + static const QString fullID() { + return "NetworkStatus"; + } + +public slots: + void getConnectionInfo(int scId, int ecId); + +private: + QNetworkInfo m_systemNetworkInfo; +}; + +#endif diff --git a/plugins/cordova-plugin-network-information/src/windows/NetworkInfoProxy.js b/plugins/cordova-plugin-network-information/src/windows/NetworkInfoProxy.js new file mode 100644 index 0000000..92153c7 --- /dev/null +++ b/plugins/cordova-plugin-network-information/src/windows/NetworkInfoProxy.js @@ -0,0 +1,83 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +/*global Windows:true */ + +var Connection = require('./Connection'); + +var winNetConn = Windows.Networking.Connectivity; +var networkInfo = winNetConn.NetworkInformation; + +function getCurrrentConnectionType() { + + var profile = networkInfo.getInternetConnectionProfile(); + + if (!profile) { + return Connection.NONE; + } + + var conLevel = profile.getNetworkConnectivityLevel(); + var interfaceType = profile.networkAdapter.ianaInterfaceType; + + // since we use this to detect whether we are online or offline we do check agains InternetAccess + // localAccess (airplane mode as an example) or constrainedInternetAccess mean there is no access to the internet available + // https://msdn.microsoft.com/library/windows/apps/windows.networking.connectivity.networkconnectivitylevel.aspx + if (conLevel != Windows.Networking.Connectivity.NetworkConnectivityLevel.internetAccess) { + return Connection.NONE; + } + + var connectionType; + + switch (interfaceType) { + case 71: + connectionType = Connection.WIFI; + break; + case 6: + connectionType = Connection.ETHERNET; + break; + case 243: // (3GPP WWAN) // Fallthrough is intentional + case 244: // (3GPP2 WWAN) + connectionType = Connection.CELL_3G; + break; + default: + connectionType = Connection.UNKNOWN; + break; + } + + return connectionType; +} + +module.exports = { + + getConnectionInfo:function(win,fail,args) + { + var reportConnectionInfoOnce = function () { + win(getCurrrentConnectionType(), { keepCallback: true }); + }; + + // report current connection type + setTimeout(reportConnectionInfoOnce, 0); + // start traking future changes + networkInfo.addEventListener("networkstatuschanged", reportConnectionInfoOnce); + } +}; + +require("cordova/exec/proxy").add("NetworkStatus",module.exports); diff --git a/plugins/cordova-plugin-network-information/src/wp/NetworkStatus.cs b/plugins/cordova-plugin-network-information/src/wp/NetworkStatus.cs new file mode 100644 index 0000000..12eb061 --- /dev/null +++ b/plugins/cordova-plugin-network-information/src/wp/NetworkStatus.cs @@ -0,0 +1,129 @@ +/* + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +using System; +using System.Diagnostics; +using System.Net; +using System.Net.NetworkInformation; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Documents; +using System.Windows.Ink; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Animation; +using System.Windows.Shapes; +using Microsoft.Phone.Net.NetworkInformation; + +namespace WPCordovaClassLib.Cordova.Commands +{ + + // http://msdn.microsoft.com/en-us/library/microsoft.phone.net.networkinformation(v=VS.92).aspx + // http://msdn.microsoft.com/en-us/library/microsoft.phone.net.networkinformation.devicenetworkinformation(v=VS.92).aspx + + public class NetworkStatus : BaseCommand + { + const string UNKNOWN = "unknown"; + const string ETHERNET = "ethernet"; + const string WIFI = "wifi"; + const string CELL_2G = "2g"; + const string CELL_3G = "3g"; + const string CELL_4G = "4g"; + const string NONE = "none"; + const string CELL = "cellular"; + + private bool HasCallback = false; + + public NetworkStatus() + { + DeviceNetworkInformation.NetworkAvailabilityChanged += new EventHandler(ChangeDetected); + } + + public override void OnResume(object sender, Microsoft.Phone.Shell.ActivatedEventArgs e) + { + this.getConnectionInfo(""); + } + + public void getConnectionInfo(string empty) + { + HasCallback = true; + updateConnectionType(checkConnectionType()); + } + + private string checkConnectionType() + { + if (DeviceNetworkInformation.IsNetworkAvailable) + { + if (DeviceNetworkInformation.IsWiFiEnabled) + { + return WIFI; + } + else + { + return DeviceNetworkInformation.IsCellularDataEnabled ? CELL : UNKNOWN; + } + } + return NONE; + } + + private string checkConnectionType(NetworkInterfaceSubType type) + { + switch (type) + { + case NetworkInterfaceSubType.Cellular_1XRTT: //cell + case NetworkInterfaceSubType.Cellular_GPRS: //cell + return CELL; + case NetworkInterfaceSubType.Cellular_EDGE: //2 + return CELL_2G; + case NetworkInterfaceSubType.Cellular_3G: + case NetworkInterfaceSubType.Cellular_EVDO: //3 + case NetworkInterfaceSubType.Cellular_EVDV: //3 + case NetworkInterfaceSubType.Cellular_HSPA: //3 + return CELL_3G; + case NetworkInterfaceSubType.WiFi: + return WIFI; + case NetworkInterfaceSubType.Unknown: + case NetworkInterfaceSubType.Desktop_PassThru: + default: + return UNKNOWN; + } + } + + void ChangeDetected(object sender, NetworkNotificationEventArgs e) + { + switch (e.NotificationType) + { + case NetworkNotificationType.InterfaceConnected: + updateConnectionType(checkConnectionType(e.NetworkInterface.InterfaceSubtype)); + break; + case NetworkNotificationType.InterfaceDisconnected: + updateConnectionType(NONE); + break; + default: + break; + } + } + + private void updateConnectionType(string type) + { + // This should also implicitly fire offline/online events as that is handled on the JS side + if (this.HasCallback) + { + PluginResult result = new PluginResult(PluginResult.Status.OK, type); + result.KeepCallback = true; + DispatchCommandResult(result); + } + } + } +} diff --git a/plugins/cordova-plugin-network-information/tests/package.json b/plugins/cordova-plugin-network-information/tests/package.json new file mode 100644 index 0000000..59b1005 --- /dev/null +++ b/plugins/cordova-plugin-network-information/tests/package.json @@ -0,0 +1,14 @@ +{ + "name": "cordova-plugin-network-information-tests", + "version": "1.3.3-dev", + "description": "", + "cordova": { + "id": "cordova-plugin-network-information-tests", + "platforms": [] + }, + "keywords": [ + "ecosystem:cordova" + ], + "author": "", + "license": "Apache 2.0" +} diff --git a/plugins/cordova-plugin-network-information/tests/plugin.xml b/plugins/cordova-plugin-network-information/tests/plugin.xml new file mode 100644 index 0000000..b847895 --- /dev/null +++ b/plugins/cordova-plugin-network-information/tests/plugin.xml @@ -0,0 +1,30 @@ + + + + + Cordova Network Information Plugin Tests + Apache 2.0 + + + + diff --git a/plugins/cordova-plugin-network-information/tests/tests.js b/plugins/cordova-plugin-network-information/tests/tests.js new file mode 100644 index 0000000..07f4b27 --- /dev/null +++ b/plugins/cordova-plugin-network-information/tests/tests.js @@ -0,0 +1,104 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +/* jshint jasmine: true */ +/* global Connection */ + +exports.defineAutoTests = function () { + describe('Network (navigator.connection)', function () { + it("network.spec.1 should exist", function () { + expect(navigator.network && navigator.network.connection).toBeDefined(); + expect(navigator.connection).toBeDefined(); + }); + + it("network.spec.2 should be set to a valid value", function () { + var validValues = { + 'unknown': 1, + 'ethernet': 1, + 'wifi': 1, + '2g': 1, + 'cellular': 1, + '3g': 1, + '4g': 1, + 'none': 1 + }; + expect(validValues[navigator.connection.type]).toBe(1); + }); + + it("network.spec.3 should have the same value in deprecated and non-deprecated apis", function () { + expect(navigator.network.connection.type).toBe(navigator.connection.type); + }); + + it("network.spec.4 should define constants for connection status", function () { + expect(Connection.UNKNOWN).toBe("unknown"); + expect(Connection.ETHERNET).toBe("ethernet"); + expect(Connection.WIFI).toBe("wifi"); + expect(Connection.CELL_2G).toBe("2g"); + expect(Connection.CELL_3G).toBe("3g"); + expect(Connection.CELL_4G).toBe("4g"); + expect(Connection.NONE).toBe("none"); + expect(Connection.CELL).toBe("cellular"); + }); + }); +}; + +/******************************************************************************/ +/******************************************************************************/ +/******************************************************************************/ + +exports.defineManualTests = function (contentEl, createActionButton) { + function eventOutput(s) { + var el = document.getElementById("results"); + el.innerHTML = el.innerHTML + s + "
"; + } + + function printNetwork() { + eventOutput("navigator.connection.type=" + navigator.connection.type); + eventOutput("navigator.network.connection.type=" + navigator.network.connection.type); + } + + function onEvent(e) { + eventOutput('Event of type: ' + e.type); + printNetwork(); + } + + /******************************************************************************/ + + var html = '
' + + 'Results:
' + + '' + + '
' + + 'Expected result: Status box will update with type of connection using two different methods. Both values must match.' + + ' The result will be unknown, ethernet, wifi, 2g, 3g, 4g, none, or cellular. Make sure it matches what the device is connected to.' + + '

'; + + document.addEventListener("online", onEvent, false); + document.addEventListener("offline", onEvent, false); + contentEl.innerHTML = html; + + createActionButton('Show Network Connection', function () { + printNetwork(); + }, 'connection'); + + createActionButton('Clear Log', function () { + document.getElementById('results').innerHTML = ''; + }, 'actions'); +}; diff --git a/plugins/cordova-plugin-network-information/types/index.d.ts b/plugins/cordova-plugin-network-information/types/index.d.ts new file mode 100644 index 0000000..60b6c26 --- /dev/null +++ b/plugins/cordova-plugin-network-information/types/index.d.ts @@ -0,0 +1,62 @@ +// Type definitions for Apache Cordova Network Information plugin +// Project: https://github.com/apache/cordova-plugin-network-information +// Definitions by: Microsoft Open Technologies Inc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// +// Copyright (c) Microsoft Open Technologies Inc +// Licensed under the MIT license + +interface Navigator { + /** + * This plugin provides an implementation of an old version of the Network Information API. + * It provides information about the device's cellular and wifi connection, and whether the device has an internet connection. + */ + connection: Connection; + // see https://github.com/apache/cordova-plugin-network-information/blob/dev/doc/index.md#api-change + // for + network: { + /** + * This plugin provides an implementation of an old version of the Network Information API. + * It provides information about the device's cellular and wifi connection, and whether the device has an internet connection. + */ + connection: Connection + } +} + +interface Document { + addEventListener(type: "online", connectionStateCallback: () => any, useCapture?: boolean): void; + addEventListener(type: "offline", connectionStateCallback: () => any, useCapture?: boolean): void; +} + +/** + * The connection object, exposed via navigator.connection, provides information + * about the device's cellular and wifi connection. + */ +interface Connection { + /** + * This property offers a fast way to determine the device's network connection state, and type of connection. + * One of: + * Connection.UNKNOWN + * Connection.ETHERNET + * Connection.WIFI + * Connection.CELL_2G + * Connection.CELL_3G + * Connection.CELL_4G + * Connection.CELL + * Connection.NONE + */ + type: string; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Connection: { + UNKNOWN: string; + ETHERNET: string; + WIFI: string; + CELL_2G: string; + CELL_3G: string; + CELL_4G: string; + CELL: string; + NONE: string; +} \ No newline at end of file diff --git a/plugins/cordova-plugin-network-information/www/Connection.js b/plugins/cordova-plugin-network-information/www/Connection.js new file mode 100644 index 0000000..f20a485 --- /dev/null +++ b/plugins/cordova-plugin-network-information/www/Connection.js @@ -0,0 +1,34 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +/** + * Network status + */ +module.exports = { + UNKNOWN: "unknown", + ETHERNET: "ethernet", + WIFI: "wifi", + CELL_2G: "2g", + CELL_3G: "3g", + CELL_4G: "4g", + CELL:"cellular", + NONE: "none" +}; diff --git a/plugins/cordova-plugin-network-information/www/network.js b/plugins/cordova-plugin-network-information/www/network.js new file mode 100644 index 0000000..ac792d8 --- /dev/null +++ b/plugins/cordova-plugin-network-information/www/network.js @@ -0,0 +1,91 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +var exec = require('cordova/exec'), + cordova = require('cordova'), + channel = require('cordova/channel'), + utils = require('cordova/utils'); + +// Link the onLine property with the Cordova-supplied network info. +// This works because we clobber the navigator object with our own +// object in bootstrap.js. +// Browser platform do not need to define this property, because +// it is already supported by modern browsers +if (cordova.platformId !== 'browser' && typeof navigator != 'undefined') { + utils.defineGetter(navigator, 'onLine', function() { + return this.connection.type != 'none'; + }); +} + +function NetworkConnection() { + this.type = 'unknown'; +} + +/** + * Get connection info + * + * @param {Function} successCallback The function to call when the Connection data is available + * @param {Function} errorCallback The function to call when there is an error getting the Connection data. (OPTIONAL) + */ +NetworkConnection.prototype.getInfo = function(successCallback, errorCallback) { + exec(successCallback, errorCallback, "NetworkStatus", "getConnectionInfo", []); +}; + +var me = new NetworkConnection(); +var timerId = null; +var timeout = 500; + +channel.createSticky('onCordovaConnectionReady'); +channel.waitForInitialization('onCordovaConnectionReady'); + +channel.onCordovaReady.subscribe(function() { + me.getInfo(function(info) { + me.type = info; + if (info === "none") { + // set a timer if still offline at the end of timer send the offline event + timerId = setTimeout(function(){ + cordova.fireDocumentEvent("offline"); + timerId = null; + }, timeout); + } else { + // If there is a current offline event pending clear it + if (timerId !== null) { + clearTimeout(timerId); + timerId = null; + } + cordova.fireDocumentEvent("online"); + } + + // should only fire this once + if (channel.onCordovaConnectionReady.state !== 2) { + channel.onCordovaConnectionReady.fire(); + } + }, + function (e) { + // If we can't get the network info we should still tell Cordova + // to fire the deviceready event. + if (channel.onCordovaConnectionReady.state !== 2) { + channel.onCordovaConnectionReady.fire(); + } + console.log("Error initializing Network Connection: " + e); + }); +}); + +module.exports = me; diff --git a/plugins/cordova-plugin-tts/README.md b/plugins/cordova-plugin-tts/README.md new file mode 100644 index 0000000..1ce65ae --- /dev/null +++ b/plugins/cordova-plugin-tts/README.md @@ -0,0 +1,63 @@ +# Cordova Text-to-Speech Plugin + +## Platforms + +iOS 7+ +Windows Phone 8 +Android 4.0.3+ (API Level 15+) + +## Installation + +```sh +cordova plugin add cordova-plugin-tts +``` + +## Usage + +```javascript +// basic usage +TTS + .speak('hello, world!', function () { + alert('success'); + }, function (reason) { + alert(reason); + }); + +// or with more options +TTS + .speak({ + text: 'hello, world!', + locale: 'en-GB', + rate: 0.75 + }, function () { + alert('success'); + }, function (reason) { + alert(reason); + }); +``` + +**Tips:** `speak` an empty string to interrupt. + +## API Definitions + +The `onfulfilled` callback will be called when the speech finishes, +and the `onrejected` callback (Windows Phone only) will be called when an error occurs. + +If the API is invoked when it's still speaking, the previous speaking will be canceled immediately, +but the `onfulfilled` callback of the previous speaking will be called when it stops. + +```typescript +declare module TTS { + interface IOptions { + /** text to speak */ + text: string; + /** a string like 'en-US', 'zh-CN', etc */ + locale?: string; + /** speed rate, 0 ~ 1 */ + rate?: number; + } + + function speak(options: IOptions, onfulfilled: () => void, onrejected: (reason) => void): void; + function speak(text: string, onfulfilled: () => void, onrejected: (reason) => void): void; +} +``` diff --git a/plugins/cordova-plugin-tts/package.json b/plugins/cordova-plugin-tts/package.json new file mode 100644 index 0000000..74676ff --- /dev/null +++ b/plugins/cordova-plugin-tts/package.json @@ -0,0 +1,32 @@ +{ + "name": "cordova-plugin-tts", + "version": "0.2.3", + "description": "Cordova Text-to-Speech Plugin", + "cordova": { + "id": "cordova-plugin-tts", + "platforms": [ + "ios", + "wp8", + "android" + ] + }, + "repository": { + "type": "git", + "url": "git+https://github.com/vilic/cordova-plugin-tts.git" + }, + "keywords": [ + "cordova", + "tts", + "text-to-speech", + "ecosystem:cordova", + "cordova-ios", + "cordova-wp8", + "cordova-android" + ], + "author": "VILIC VANE", + "license": "MIT", + "bugs": { + "url": "https://github.com/vilic/cordova-plugin-tts/issues" + }, + "homepage": "https://github.com/vilic/cordova-plugin-tts#readme" +} diff --git a/plugins/cordova-plugin-tts/plugin.xml b/plugins/cordova-plugin-tts/plugin.xml new file mode 100644 index 0000000..2d15e54 --- /dev/null +++ b/plugins/cordova-plugin-tts/plugin.xml @@ -0,0 +1,58 @@ + + + + TTS + Cordova Text-to-Speech Plugin + VILIC VANE + MIT + cordova,tts,text-to-speech + https://github.com/vilic/cordova-plugin-tts.git + https://github.com/vilic/cordova-plugin-tts/issues + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/cordova-plugin-tts/src/android/TTS.java b/plugins/cordova-plugin-tts/src/android/TTS.java new file mode 100644 index 0000000..871fe3a --- /dev/null +++ b/plugins/cordova-plugin-tts/src/android/TTS.java @@ -0,0 +1,144 @@ +package com.wordsbaking.cordova.tts; + +import org.apache.cordova.CallbackContext; +import org.apache.cordova.CordovaPlugin; + +import org.apache.cordova.CordovaWebView; +import org.apache.cordova.CordovaInterface; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import android.speech.tts.TextToSpeech; +import android.speech.tts.TextToSpeech.OnInitListener; +import android.speech.tts.UtteranceProgressListener; + +import java.util.HashMap; +import java.util.Locale; + +/* + Cordova Text-to-Speech Plugin + https://github.com/vilic/cordova-plugin-tts + + by VILIC VANE + https://github.com/vilic + + MIT License +*/ + +public class TTS extends CordovaPlugin implements OnInitListener { + + public static final String ERR_INVALID_OPTIONS = "ERR_INVALID_OPTIONS"; + public static final String ERR_NOT_INITIALIZED = "ERR_NOT_INITIALIZED"; + public static final String ERR_ERROR_INITIALIZING = "ERR_ERROR_INITIALIZING"; + public static final String ERR_UNKNOWN = "ERR_UNKNOWN"; + + boolean ttsInitialized = false; + TextToSpeech tts = null; + + @Override + public void initialize(CordovaInterface cordova, final CordovaWebView webView) { + tts = new TextToSpeech(cordova.getActivity().getApplicationContext(), this); + tts.setOnUtteranceProgressListener(new UtteranceProgressListener() { + @Override + public void onStart(String s) { + // do nothing + } + + @Override + public void onDone(String callbackId) { + if (!callbackId.equals("")) { + CallbackContext context = new CallbackContext(callbackId, webView); + context.success(); + } + } + + @Override + public void onError(String callbackId) { + if (!callbackId.equals("")) { + CallbackContext context = new CallbackContext(callbackId, webView); + context.error(ERR_UNKNOWN); + } + } + }); + } + + @Override + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) + throws JSONException { + if (action.equals("speak")) { + speak(args, callbackContext); + } else { + return false; + } + return true; + } + + @Override + public void onInit(int status) { + if (status != TextToSpeech.SUCCESS) { + tts = null; + } else { + // warm up the tts engine with an empty string + HashMap ttsParams = new HashMap(); + ttsParams.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, ""); + tts.setLanguage(new Locale("en", "US")); + tts.speak("", TextToSpeech.QUEUE_FLUSH, ttsParams); + + ttsInitialized = true; + } + } + + private void speak(JSONArray args, CallbackContext callbackContext) + throws JSONException, NullPointerException { + JSONObject params = args.getJSONObject(0); + + if (params == null) { + callbackContext.error(ERR_INVALID_OPTIONS); + return; + } + + String text; + String locale; + double rate; + + if (params.isNull("text")) { + callbackContext.error(ERR_INVALID_OPTIONS); + return; + } else { + text = params.getString("text"); + } + + if (params.isNull("locale")) { + locale = "en-US"; + } else { + locale = params.getString("locale"); + } + + if (params.isNull("rate")) { + rate = 1.0; + } else { + rate = params.getDouble("rate"); + } + + if (tts == null) { + callbackContext.error(ERR_ERROR_INITIALIZING); + return; + } + + if (!ttsInitialized) { + callbackContext.error(ERR_NOT_INITIALIZED); + return; + } + + HashMap ttsParams = new HashMap(); + ttsParams.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, callbackContext.getCallbackId()); + + String[] localeArgs = locale.split("-"); + tts.setLanguage(new Locale(localeArgs[0], localeArgs[1])); + tts.setSpeechRate((float) rate); + + tts.speak(text, TextToSpeech.QUEUE_FLUSH, ttsParams); + } +} \ No newline at end of file diff --git a/plugins/cordova-plugin-tts/src/ios/CDVTTS.h b/plugins/cordova-plugin-tts/src/ios/CDVTTS.h new file mode 100644 index 0000000..4bd3cd3 --- /dev/null +++ b/plugins/cordova-plugin-tts/src/ios/CDVTTS.h @@ -0,0 +1,21 @@ +/* + Cordova Text-to-Speech Plugin + https://github.com/vilic/cordova-plugin-tts + + by VILIC VANE + https://github.com/vilic + + MIT License + */ + +#import +#import + +@interface CDVTTS : CDVPlugin { + AVSpeechSynthesizer* synthesizer; + NSString* lastCallbackId; + NSString* callbackId; +} + +- (void)speak:(CDVInvokedUrlCommand*)command; +@end diff --git a/plugins/cordova-plugin-tts/src/ios/CDVTTS.m b/plugins/cordova-plugin-tts/src/ios/CDVTTS.m new file mode 100644 index 0000000..0197016 --- /dev/null +++ b/plugins/cordova-plugin-tts/src/ios/CDVTTS.m @@ -0,0 +1,72 @@ +/* + Cordova Text-to-Speech Plugin + https://github.com/vilic/cordova-plugin-tts + + by VILIC VANE + https://github.com/vilic + + MIT License +*/ + +#import +#import "CDVTTS.h" + +@implementation CDVTTS + +- (void)pluginInitialize { + synthesizer = [AVSpeechSynthesizer new]; + synthesizer.delegate = self; +} + +- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance*)utterance { + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + if (lastCallbackId) { + [self.commandDelegate sendPluginResult:result callbackId:lastCallbackId]; + lastCallbackId = nil; + } else { + [self.commandDelegate sendPluginResult:result callbackId:callbackId]; + callbackId = nil; + } + + [[AVAudioSession sharedInstance] setActive:NO withOptions:0 error:nil]; + [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient + withOptions: 0 error: nil]; + [[AVAudioSession sharedInstance] setActive:YES withOptions: 0 error:nil]; +} + +- (void)speak:(CDVInvokedUrlCommand*)command { + [[AVAudioSession sharedInstance] setActive:NO withOptions:0 error:nil]; + [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback + withOptions:AVAudioSessionCategoryOptionDuckOthers error:nil]; + + if (callbackId) { + lastCallbackId = callbackId; + } + + callbackId = command.callbackId; + + [synthesizer stopSpeakingAtBoundary:AVSpeechBoundaryImmediate]; + + NSDictionary* options = [command.arguments objectAtIndex:0]; + + NSString* text = [options objectForKey:@"text"]; + NSString* locale = [options objectForKey:@"locale"]; + double rate = [[options objectForKey:@"rate"] doubleValue]; + + if (!locale || (id)locale == [NSNull null]) { + locale = @"en-US"; + } + + if (!rate) { + rate = 1.0; + } + + AVSpeechUtterance* utterance = [[AVSpeechUtterance new] initWithString:text]; + utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:locale]; + // Rate expression adjusted manually for a closer match to other platform. + utterance.rate = (AVSpeechUtteranceMinimumSpeechRate * 1.5 + AVSpeechUtteranceDefaultSpeechRate) / 2.5 * rate * rate; + utterance.pitchMultiplier = 1.2; + [synthesizer speakUtterance:utterance]; +} + +@end diff --git a/plugins/cordova-plugin-tts/src/wp/TTS.cs b/plugins/cordova-plugin-tts/src/wp/TTS.cs new file mode 100644 index 0000000..bfb3c31 --- /dev/null +++ b/plugins/cordova-plugin-tts/src/wp/TTS.cs @@ -0,0 +1,78 @@ +/* + Cordova Text-to-Speech Plugin + https://github.com/vilic/cordova-plugin-tts + + by VILIC VANE + https://github.com/vilic + + MIT License +*/ + +using System; +using System.Diagnostics; +using System.Runtime.Serialization; +using System.Threading.Tasks; +using Windows.Phone.Speech.Synthesis; +using WPCordovaClassLib.Cordova; +using WPCordovaClassLib.Cordova.Commands; +using WPCordovaClassLib.Cordova.JSON; + +namespace Cordova.Extension.Commands { + [DataContract] + class Options { + [DataMember] + public string text; + [DataMember] + public string locale; + [DataMember] + public double? rate; + } + + class TTS : BaseCommand { + SpeechSynthesizer synth = new SpeechSynthesizer(); + + string lastCallbackId; + + public async void speak(string argsJSON) { + if (lastCallbackId != null) { + DispatchCommandResult(new PluginResult(PluginResult.Status.OK), lastCallbackId); + lastCallbackId = null; + synth.CancelAll(); + } + + var args = JsonHelper.Deserialize(argsJSON); + var options = JsonHelper.Deserialize(args[0]); + lastCallbackId = args[1]; + + var locale = options.locale != null ? options.locale : "en-US"; + var rate = options.rate != null ? options.rate : 1.0; + + var ssml = +@" + + " + xmlEncode(options.text) + @" +"; + + try { + await synth.SpeakSsmlAsync(ssml); + lastCallbackId = null; + DispatchCommandResult(new PluginResult(PluginResult.Status.OK)); + } catch (OperationCanceledException) { + // do nothing + } catch (Exception e) { + Debug.WriteLine(e.Message); + lastCallbackId = null; + DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, e.Message)); + } + } + + string xmlEncode(string text) { + return text + .Replace("&", "&") + .Replace("<", "<") + .Replace(">", ">"); + } + } +} diff --git a/plugins/cordova-plugin-tts/www/tts.js b/plugins/cordova-plugin-tts/www/tts.js new file mode 100644 index 0000000..046ff0e --- /dev/null +++ b/plugins/cordova-plugin-tts/www/tts.js @@ -0,0 +1,28 @@ +/* + + Cordova Text-to-Speech Plugin + https://github.com/vilic/cordova-plugin-tts + + by VILIC VANE + https://github.com/vilic + + MIT License + +*/ + +exports.speak = function (text, onfulfilled, onrejected) { + var options = {}; + + if (typeof text == 'string') { + options.text = text; + } else { + options = text; + } + + cordova + .exec(function () { + onfulfilled(); + }, function (reason) { + onrejected(reason); + }, 'TTS', 'speak', [options]); +}; \ No newline at end of file diff --git a/plugins/cordova-plugin-whitelist/CONTRIBUTING.md b/plugins/cordova-plugin-whitelist/CONTRIBUTING.md new file mode 100644 index 0000000..7de4c64 --- /dev/null +++ b/plugins/cordova-plugin-whitelist/CONTRIBUTING.md @@ -0,0 +1,37 @@ + + +# Contributing to Apache Cordova + +Anyone can contribute to Cordova. And we need your contributions. + +There are multiple ways to contribute: report bugs, improve the docs, and +contribute code. + +For instructions on this, start with the +[contribution overview](http://cordova.apache.org/contribute/). + +The details are explained there, but the important items are: + - Sign and submit an Apache ICLA (Contributor License Agreement). + - Have a Jira issue open that corresponds to your contribution. + - Run the tests so your patch doesn't break existing functionality. + +We look forward to your contributions! diff --git a/plugins/cordova-plugin-whitelist/LICENSE b/plugins/cordova-plugin-whitelist/LICENSE new file mode 100644 index 0000000..7a4a3ea --- /dev/null +++ b/plugins/cordova-plugin-whitelist/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/plugins/cordova-plugin-whitelist/NOTICE b/plugins/cordova-plugin-whitelist/NOTICE new file mode 100644 index 0000000..8ec56a5 --- /dev/null +++ b/plugins/cordova-plugin-whitelist/NOTICE @@ -0,0 +1,5 @@ +Apache Cordova +Copyright 2012 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). diff --git a/plugins/cordova-plugin-whitelist/README.md b/plugins/cordova-plugin-whitelist/README.md new file mode 100644 index 0000000..e19d230 --- /dev/null +++ b/plugins/cordova-plugin-whitelist/README.md @@ -0,0 +1,163 @@ +--- +title: Whitelist +description: Whitelist external content accessible by your app. +--- + + +# cordova-plugin-whitelist + +This plugin implements a whitelist policy for navigating the application webview on Cordova 4.0 + +:warning: Report issues on the [Apache Cordova issue tracker](https://issues.apache.org/jira/issues/?jql=project%20%3D%20CB%20AND%20status%20in%20%28Open%2C%20%22In%20Progress%22%2C%20Reopened%29%20AND%20resolution%20%3D%20Unresolved%20AND%20component%20%3D%20%22Plugin%20Whitelist%22%20ORDER%20BY%20priority%20DESC%2C%20summary%20ASC%2C%20updatedDate%20DESC) + +## Installation + +You can install whitelist plugin with Cordova CLI, from npm: + +``` +$ cordova plugin add cordova-plugin-whitelist +$ cordova prepare +``` + +## Supported Cordova Platforms + +* Android 4.0.0 or above + +## Navigation Whitelist +Controls which URLs the WebView itself can be navigated to. Applies to +top-level navigations only. + +Quirks: on Android it also applies to iframes for non-http(s) schemes. + +By default, navigations only to `file://` URLs, are allowed. To allow others URLs, you must add `` tags to your `config.xml`: + + + + + + + + + + + + + + + +## Intent Whitelist +Controls which URLs the app is allowed to ask the system to open. +By default, no external URLs are allowed. + +On Android, this equates to sending an intent of type BROWSEABLE. + +This whitelist does not apply to plugins, only hyperlinks and calls to `window.open()`. + +In `config.xml`, add `` tags, like this: + + + + + + + + + + + + + + + + + + + + + + + +## Network Request Whitelist +Controls which network requests (images, XHRs, etc) are allowed to be made (via cordova native hooks). + +Note: We suggest you use a Content Security Policy (see below), which is more secure. This whitelist is mostly historical for webviews which do not support CSP. + +In `config.xml`, add `` tags, like this: + + + + + + + + + + + + + + + + + +Without any `` tags, only requests to `file://` URLs are allowed. However, the default Cordova application includes `` by default. + + +Note: Whitelist cannot block network redirects from a whitelisted remote website (i.e. http or https) to a non-whitelisted website. Use CSP rules to mitigate redirects to non-whitelisted websites for webviews that support CSP. + +Quirk: Android also allows requests to https://ssl.gstatic.com/accessibility/javascript/android/ by default, since this is required for TalkBack to function properly. + +### Content Security Policy +Controls which network requests (images, XHRs, etc) are allowed to be made (via webview directly). + +On Android and iOS, the network request whitelist (see above) is not able to filter all types of requests (e.g. `