diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 000000000..d24b0a8cf --- /dev/null +++ b/.eslintignore @@ -0,0 +1 @@ +www/Promise.js diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 000000000..bd081fe45 --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,42 @@ +module.exports = { + "env": { + "browser": true, + "node": true + }, + "extends": "eslint:recommended", + "parserOptions": { + "ecmaVersion": 5 + }, + "rules": { + "indent": [ + "error", + 2 + ], + "linebreak-style": [ + "error", + "unix" + ], + "quotes": [ + "error", + "single" + ], + "semi": [ + "error", + "always" + ], + "no-console": 0 + }, + "globals": { + "require": false, + "Symbol": false, + "window": false, + "cordova": false, + "Promise": false, + "module": false, + "angular": false, + "firebase": false, + "exports": false, + "google": false, + "plugin": false + } +}; diff --git a/package.json b/package.json index 16ae89782..b2e360f06 100644 --- a/package.json +++ b/package.json @@ -42,10 +42,17 @@ "version": ">=10.0.0" } ], + "scripts": { + "test": "npm run eslint", + "eslint": "node node_modules/eslint/bin/eslint www && node node_modules/eslint/bin/eslint src" + }, "author": "Masashi Katsumata, Hirbod Mirjavadi", "license": "Apache 2.0", "bugs": { "url": "https://github.com/mapsplugin/cordova-plugin-googlemaps/issues" }, - "homepage": "https://github.com/mapsplugin/cordova-plugin-googlemaps" + "homepage": "https://github.com/mapsplugin/cordova-plugin-googlemaps", + "dependencies": { + "eslint": "^5.7.0" + } } diff --git a/src/after_plugin_install.js b/src/after_plugin_install.js index d281f1f1e..e21a0638f 100644 --- a/src/after_plugin_install.js +++ b/src/after_plugin_install.js @@ -8,16 +8,16 @@ module.exports = function(ctx) { } var fs = ctx.requireCordovaModule('fs'), - path = ctx.requireCordovaModule('path'), - Q = ctx.requireCordovaModule('q'); + path = ctx.requireCordovaModule('path'), + Q = ctx.requireCordovaModule('q'); var pluginXmlPath = path.join(__dirname, '..', 'plugin.xml'); - return Q.Promise(function(resolve, reject, notify) { + return Q.Promise(function(resolve, reject) { // Copy the original plugin.xml to the current plugin.xml return fs.createReadStream(pluginXmlPath + '.original') - .pipe(fs.createWriteStream(pluginXmlPath)) - .on("error", reject) - .on("close", resolve); + .pipe(fs.createWriteStream(pluginXmlPath)) + .on('error', reject) + .on('close', resolve); }); }; diff --git a/src/before_plugin_install.js b/src/before_plugin_install.js index 1bd5411a2..2fba6e0fd 100644 --- a/src/before_plugin_install.js +++ b/src/before_plugin_install.js @@ -1,8 +1,8 @@ module.exports = function(ctx) { var fs = ctx.requireCordovaModule('fs'), - path = ctx.requireCordovaModule('path'), - Q = ctx.requireCordovaModule('q'); + path = ctx.requireCordovaModule('path'), + Q = ctx.requireCordovaModule('q'); var projectRoot = ctx.opts.projectRoot, configXmlPath = path.join(projectRoot, 'config.xml'), pluginXmlPath = path.join(__dirname, '..', 'plugin.xml'); @@ -21,15 +21,15 @@ module.exports = function(ctx) { var oldPaths = Module._nodeModulePaths(projectRoot); if (oldPaths.indexOf(NODE_MODULES_DIR) === -1) { Module._nodeModulePaths = function(from) { - var paths = old_nodeModulePaths.call(this, from); - paths.push(NODE_MODULES_DIR); - return paths; + var paths = old_nodeModulePaths.call(this, from); + paths.push(NODE_MODULES_DIR); + return paths; }; } } - return Q.Promise(function(resolve, reject, notify) { + return Q.Promise(function(resolve, reject) { var exec = require('child_process').exec; exec('npm install xml2js@0.4.19 minimist@1.2.0 --save 2>&1', function(err, stdout) { if (err) { @@ -40,172 +40,172 @@ module.exports = function(ctx) { } }); }) - .then(function() { - return Q.Promise(function(resolve, reject, notify) { - if (fs.existsSync(pluginXmlPath + '.original')) { + .then(function() { + return Q.Promise(function(resolve, reject) { + if (fs.existsSync(pluginXmlPath + '.original')) { // Copy the original plugin.xml to the current plugin.xml - return fs.createReadStream(pluginXmlPath + '.original') + return fs.createReadStream(pluginXmlPath + '.original') .pipe(fs.createWriteStream(pluginXmlPath)) - .on("error", reject) - .on("close", resolve); - } else { + .on('error', reject) + .on('close', resolve); + } else { // Backup the original plugin.xml file - return fs.createReadStream(pluginXmlPath) + return fs.createReadStream(pluginXmlPath) .pipe(fs.createWriteStream(pluginXmlPath + '.original')) - .on("error", reject) - .on("close", resolve); - } - }); - }) - .then(function() { - return Q.Promise(function(resolve, reject, notify) { + .on('error', reject) + .on('close', resolve); + } + }); + }) + .then(function() { + return Q.Promise(function(resolve, reject) { //--------------------------- // Read the config.xml file //--------------------------- - fs.readFile(configXmlPath, function(error, data) { - if (error) { - reject(error); - } else { + fs.readFile(configXmlPath, function(error, data) { + if (error) { + reject(error); + } else { - //--------------------------- - // Parse the xml data - //--------------------------- - var xml2js = require('xml2js'); - var xmlParser = new xml2js.Parser(); - xmlParser.parseString(data + "", function(error, configXmlData) { - if (error) { - reject(error); - } else { - resolve(configXmlData); - } - }); - } + //--------------------------- + // Parse the xml data + //--------------------------- + var xml2js = require('xml2js'); + var xmlParser = new xml2js.Parser(); + xmlParser.parseString(data + '', function(error, configXmlData) { + if (error) { + reject(error); + } else { + resolve(configXmlData); + } + }); + } + }); }); - }); - }) - .then(function(configXmlData) { + }) + .then(function(configXmlData) { //------------------------------------------------------------------------------ // Check the xml data. // If there is no definition of this plugin in the config.xml, // then insert some dummy data in order to prevent the API_KEY_FOR_ANDROID error. //------------------------------------------------------------------------------ - return Q.Promise(function(resolve, reject, notify) { - var hasPluginGoogleMaps = false; - configXmlData.widget.plugin = configXmlData.widget.plugin || []; - configXmlData.widget.plugin = configXmlData.widget.plugin.map(function(plugin) { - if (plugin.$.name !== "cordova-plugin-googlemaps") { - return plugin; - } + return Q.Promise(function(resolve) { + var hasPluginGoogleMaps = false; + configXmlData.widget.plugin = configXmlData.widget.plugin || []; + configXmlData.widget.plugin = configXmlData.widget.plugin.map(function(plugin) { + if (plugin.$.name !== 'cordova-plugin-googlemaps') { + return plugin; + } - hasPluginGoogleMaps = true; - var variables = {}; - plugin.variable = plugin.variable || []; - plugin.variable.forEach(function(variable) { - variables[variable.$.name] = variable.$.value; - }); - if (!('API_KEY_FOR_ANDROID' in variables)) { - plugin.variable.push({ - '$' : { - 'name': 'API_KEY_FOR_ANDROID', - 'value': '(API_KEY_FOR_ANDROID)' - } + hasPluginGoogleMaps = true; + var variables = {}; + plugin.variable = plugin.variable || []; + plugin.variable.forEach(function(variable) { + variables[variable.$.name] = variable.$.value; }); - } - if (!('API_KEY_FOR_IOS' in variables)) { - plugin.variable.push({ + if (!('API_KEY_FOR_ANDROID' in variables)) { + plugin.variable.push({ + '$' : { + 'name': 'API_KEY_FOR_ANDROID', + 'value': '(API_KEY_FOR_ANDROID)' + } + }); + } + if (!('API_KEY_FOR_IOS' in variables)) { + plugin.variable.push({ + '$' : { + 'name': 'API_KEY_FOR_IOS', + 'value': '(API_KEY_FOR_IOS)' + } + }); + } + return plugin; + }); + + if (!hasPluginGoogleMaps) { + configXmlData.widget.plugin.push({ '$' : { - 'name': 'API_KEY_FOR_IOS', - 'value': '(API_KEY_FOR_IOS)' - } + 'name': 'cordova-plugin-googlemaps', + 'spec': 'dummy' + }, + 'variable' : [ + {'$': { + 'name': 'API_KEY_FOR_ANDROID', + 'value': '(API_KEY_FOR_ANDROID)' + } + }, + { + '$': { + 'name': 'API_KEY_FOR_IOS', + 'value': '(API_KEY_FOR_IOS)' + } + } + ] }); } - return plugin; + resolve(configXmlData); }); - - if (!hasPluginGoogleMaps) { - configXmlData.widget.plugin.push({ - '$' : { - 'name': 'cordova-plugin-googlemaps', - 'spec': 'dummy' - }, - 'variable' : [ - {"$": { - "name": "API_KEY_FOR_ANDROID", - "value": "(API_KEY_FOR_ANDROID)" - } - }, - { - "$": { - "name": "API_KEY_FOR_IOS", - "value": "(API_KEY_FOR_IOS)" - } - } - ] - }); - } - resolve(configXmlData); - }); - }) - .then(function(configXmlData) { - return Q.Promise(function(resolve, reject, notify) { + }) + .then(function(configXmlData) { + return Q.Promise(function(resolve, reject) { //--------------------------- // Read the plugin.xml file //--------------------------- - fs.readFile(pluginXmlPath, function(error, data) { - if (error) { - reject(error); - } else { + fs.readFile(pluginXmlPath, function(error, data) { + if (error) { + reject(error); + } else { //--------------------------- // Parse the xml data //--------------------------- - var xml2js = require('xml2js'); - var xmlParser = new xml2js.Parser(); - xmlParser.parseString(data + "", function(error, pluginXmlData) { - if (error) { - reject(error); - } else { - resolve({ - configXmlData: configXmlData, - pluginXmlData: pluginXmlData, - pluginXmlTxt: data + "" - }); - } - }); - } + var xml2js = require('xml2js'); + var xmlParser = new xml2js.Parser(); + xmlParser.parseString(data + '', function(error, pluginXmlData) { + if (error) { + reject(error); + } else { + resolve({ + configXmlData: configXmlData, + pluginXmlData: pluginXmlData, + pluginXmlTxt: data + '' + }); + } + }); + } + }); }); - }); - }) - .then(function(params) { - return Q.Promise(function(resolve, reject, notify) { + }) + .then(function(params) { + return Q.Promise(function(resolve, reject) { //------------------------------ // Read the install variables //------------------------------ - var mapsPlugin = params.configXmlData.widget.plugin.filter(function(plugin) { - return (plugin.$.name === "cordova-plugin-googlemaps"); - })[0]; - var variables = {}; - mapsPlugin.variable.forEach(function(variable) { - variables[variable.$.name] = variable.$.value; - }); + var mapsPlugin = params.configXmlData.widget.plugin.filter(function(plugin) { + return (plugin.$.name === 'cordova-plugin-googlemaps'); + })[0]; + var variables = {}; + mapsPlugin.variable.forEach(function(variable) { + variables[variable.$.name] = variable.$.value; + }); - //------------------------------ - // Read default preferences - //------------------------------ - var findPreference = function(xmlData) { - var results = {}; - var keys = Object.keys(xmlData); - keys.forEach(function(tagName) { - switch(tagName) { - case "$": - case "js-module": - case "engines": - case "config-file": - case "info": + //------------------------------ + // Read default preferences + //------------------------------ + var findPreference = function(xmlData) { + var results = {}; + var keys = Object.keys(xmlData); + keys.forEach(function(tagName) { + switch(tagName) { + case '$': + case 'js-module': + case 'engines': + case 'config-file': + case 'info': //ignore break; - case "preference": + case 'preference': if (Array.isArray(xmlData[tagName])) { xmlData[tagName].forEach(function(node) { results[node.$.name] = node.$.default; @@ -215,7 +215,7 @@ module.exports = function(ctx) { } break; - case "plugin": + case 'plugin': results = findPreference(xmlData.plugin); break; @@ -225,41 +225,41 @@ module.exports = function(ctx) { results = Object.assign(findPreference(node), results); }); } - } - }); - return results; - }; - var pluginDefaults = findPreference(params.pluginXmlData); - variables = Object.assign(pluginDefaults, variables); - - //---------------------------------- - // Parse the command line variables - //---------------------------------- - if (ctx.cmdLine.includes("cordova plugin add")) { - var phrses = require('minimist')(ctx.cmdLine.split(' ')); - if (Array.isArray(phrses.variable)) { - phrses.variable.forEach(function(line) { - var tmp = line.split("="); - variables[tmp[0]] = tmp[1]; + } }); + return results; + }; + var pluginDefaults = findPreference(params.pluginXmlData); + variables = Object.assign(pluginDefaults, variables); + + //---------------------------------- + // Parse the command line variables + //---------------------------------- + if (ctx.cmdLine.includes('cordova plugin add')) { + var phrses = require('minimist')(ctx.cmdLine.split(' ')); + if (Array.isArray(phrses.variable)) { + phrses.variable.forEach(function(line) { + var tmp = line.split('='); + variables[tmp[0]] = tmp[1]; + }); + } } - } - //-------------------------------- - // Override the plugin.xml itself - //-------------------------------- - params.pluginXmlTxt = params.pluginXmlTxt.replace(/\$([A-Z0-9\_]+)/g, function(matchWhole, varName) { - return variables[varName] || matchWhole; - }); + //-------------------------------- + // Override the plugin.xml itself + //-------------------------------- + params.pluginXmlTxt = params.pluginXmlTxt.replace(/\$([A-Z0-9_]+)/g, function(matchWhole, varName) { + return variables[varName] || matchWhole; + }); - fs.writeFile(pluginXmlPath, params.pluginXmlTxt, 'utf8', function(error) { - if (error) { - reject(error); - } else { - resolve(); - } + fs.writeFile(pluginXmlPath, params.pluginXmlTxt, 'utf8', function(error) { + if (error) { + reject(error); + } else { + resolve(); + } + }); }); }); - }); }; diff --git a/src/before_plugin_rm.js b/src/before_plugin_rm.js index 1453e5add..80417c467 100644 --- a/src/before_plugin_rm.js +++ b/src/before_plugin_rm.js @@ -8,8 +8,8 @@ module.exports = function(ctx) { } var fs = ctx.requireCordovaModule('fs'), - path = ctx.requireCordovaModule('path'), - Q = ctx.requireCordovaModule('q'); + path = ctx.requireCordovaModule('path'), + Q = ctx.requireCordovaModule('q'); var projectRoot = ctx.opts.projectRoot, configXmlPath = path.join(projectRoot, 'config.xml'); @@ -20,9 +20,9 @@ module.exports = function(ctx) { var oldPaths = Module._nodeModulePaths(projectRoot); if (oldPaths.indexOf(NODE_MODULES_DIR) === -1) { Module._nodeModulePaths = function(from) { - var paths = old_nodeModulePaths.call(this, from); - paths.push(NODE_MODULES_DIR); - return paths; + var paths = old_nodeModulePaths.call(this, from); + paths.push(NODE_MODULES_DIR); + return paths; }; } } @@ -43,7 +43,7 @@ module.exports = function(ctx) { } }; - return Q.Promise(function(resolve, reject, notify) { + return Q.Promise(function(resolve, reject) { //--------------------------- // Read the config.xml file //--------------------------- @@ -51,114 +51,111 @@ module.exports = function(ctx) { if (error) { reject(error); } else { - resolve(data + ""); + resolve(data + ''); } }); }) - .then(function(data) { + .then(function(data) { //--------------------------- // Parse the xml data //--------------------------- - return Q.Promise(function(resolve, reject, notify) { - var xmlParser = new xml2js.Parser(); - xmlParser.parseString(data, function(error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); + return Q.Promise(function(resolve, reject) { + var xmlParser = new xml2js.Parser(); + xmlParser.parseString(data, function(error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); - }); - }) - .then(function(data) { + }); + }) + .then(function(data) { //------------------------------------------------------------------------------ // Check the xml data. // If there is no definition of this plugin in the config.xml, // then insert some dummy data in order to prevent the API_KEY_FOR_ANDROID error. //------------------------------------------------------------------------------ - return Q.Promise(function(resolve, reject, notify) { - var hasPluginGoogleMaps = false; - data.widget.plugin = data.widget.plugin || []; - data.widget.plugin = data.widget.plugin.map(function(plugin) { - if (plugin.$.name !== "cordova-plugin-googlemaps") { - return plugin; - } + return Q.Promise(function(resolve) { + var hasPluginGoogleMaps = false; + data.widget.plugin = data.widget.plugin || []; + data.widget.plugin = data.widget.plugin.map(function(plugin) { + if (plugin.$.name !== 'cordova-plugin-googlemaps') { + return plugin; + } - hasPluginGoogleMaps = true; - var variables = {}; - plugin.variable = plugin.variable || []; - plugin.variable.forEach(function(variable) { - variables[variable.$.name] = variable.$.value; - }); - if (!('API_KEY_FOR_ANDROID' in variables)) { - plugin.variable.push({ - '$' : { - 'name': 'API_KEY_FOR_ANDROID', - 'value': '(API_KEY_FOR_ANDROID)' - } + hasPluginGoogleMaps = true; + var variables = {}; + plugin.variable = plugin.variable || []; + plugin.variable.forEach(function(variable) { + variables[variable.$.name] = variable.$.value; }); - } - if (!('API_KEY_FOR_IOS' in variables)) { - plugin.variable.push({ + if (!('API_KEY_FOR_ANDROID' in variables)) { + plugin.variable.push({ + '$' : { + 'name': 'API_KEY_FOR_ANDROID', + 'value': '(API_KEY_FOR_ANDROID)' + } + }); + } + if (!('API_KEY_FOR_IOS' in variables)) { + plugin.variable.push({ + '$' : { + 'name': 'API_KEY_FOR_IOS', + 'value': '(API_KEY_FOR_IOS)' + } + }); + } + return plugin; + }); + + if (!hasPluginGoogleMaps) { + data.widget.plugin.push({ '$' : { - 'name': 'API_KEY_FOR_IOS', - 'value': '(API_KEY_FOR_IOS)' - } + 'name': 'cordova-plugin-googlemaps', + 'spec': 'dummy' + }, + 'variable' : [ + {'$': { + 'name': 'API_KEY_FOR_ANDROID', + 'value': '(API_KEY_FOR_ANDROID)' + } + }, + { + '$': { + 'name': 'API_KEY_FOR_IOS', + 'value': '(API_KEY_FOR_IOS)' + } + } + ] }); } - return plugin; + resolve(data); }); - - if (!hasPluginGoogleMaps) { - data.widget.plugin.push({ - '$' : { - 'name': 'cordova-plugin-googlemaps', - 'spec': 'dummy' - }, - 'variable' : [ - {"$": { - "name": "API_KEY_FOR_ANDROID", - "value": "(API_KEY_FOR_ANDROID)" - } - }, - { - "$": { - "name": "API_KEY_FOR_IOS", - "value": "(API_KEY_FOR_IOS)" - } - } - ] - }); - } - resolve(data); - }); - }) - .then(function(data) { + }) + .then(function(data) { //--------------------------- // Override the config.xml //--------------------------- - return Q.Promise(function(resolve, reject, notify) { - var builder = new xml2js.Builder(); - var xml = builder.buildObject(data); - fs.writeFile(configXmlPath, xml, 'utf8', function(error) { - if (error) { - reject(error); - } else { - resolve(); - } + return Q.Promise(function(resolve, reject) { + var builder = new xml2js.Builder(); + var xml = builder.buildObject(data); + fs.writeFile(configXmlPath, xml, 'utf8', function(error) { + if (error) { + reject(error); + } else { + resolve(); + } + }); }); - }); - }) - .then(function() { - return Q.Promise(function(resolve, reject, notify) { + }) + .then(function() { ctx.opts.cordova.platforms.forEach(function(platformName) { rmdir(path.join(projectRoot, 'platforms', platformName, 'platform_www', 'plugins', 'cordova-plugin-googlemaps')); rmdir(path.join(projectRoot, 'platforms', platformName, 'www', 'plugins', 'cordova-plugin-googlemaps')); }); - resolve(); }); - }); }; diff --git a/src/browser/CordovaGoogleMaps.js b/src/browser/CordovaGoogleMaps.js index e2823e252..393e6f1ba 100644 --- a/src/browser/CordovaGoogleMaps.js +++ b/src/browser/CordovaGoogleMaps.js @@ -2,16 +2,15 @@ var PluginMap = require('cordova-plugin-googlemaps.PluginMap'), - PluginStreetViewPanorama = require('cordova-plugin-googlemaps.PluginStreetViewPanorama'), - event = require('cordova-plugin-googlemaps.event'), - Environment = require('cordova-plugin-googlemaps.PluginEnvironment'); + PluginStreetViewPanorama = require('cordova-plugin-googlemaps.PluginStreetViewPanorama'), + event = require('cordova-plugin-googlemaps.event'), + Environment = require('cordova-plugin-googlemaps.PluginEnvironment'); -var MAP_CNT = 0; var MAPS = {}; var API_LOADED_STATUS = 0; // 0: not loaded, 1: loading, 2: completed -document.addEventListener("load_googlemaps", function() { +document.addEventListener('load_googlemaps', function() { var envOptions = Environment._getEnv(); var API_KEY_FOR_BROWSER; if (envOptions) { @@ -30,27 +29,27 @@ document.addEventListener("load_googlemaps", function() { // for development only secureStripeScript.setAttribute('src','https://maps.googleapis.com/maps/api/js'); } - secureStripeScript.addEventListener("load", function() { + secureStripeScript.addEventListener('load', function() { API_LOADED_STATUS = 2; var mKeys = Object.keys(MAPS); mKeys.forEach(function(mkey) { var map = MAPS[mkey]; - if (!map.get("isGoogleReady")) { - map.trigger("googleready"); + if (!map.get('isGoogleReady')) { + map.trigger('googleready'); } }); }); - secureStripeScript.addEventListener("error", function(error) { - console.log("Can not load the Google Maps JavaScript API v3"); + secureStripeScript.addEventListener('error', function(error) { + console.log('Can not load the Google Maps JavaScript API v3'); console.log(error); var mKeys = Object.keys(MAPS); mKeys.forEach(function(mkey) { var map = MAPS[mkey]; if (map) { - map.trigger("load_error"); + map.trigger('load_error'); } }); }); @@ -72,7 +71,7 @@ var CordovaGoogleMaps = { // memory cleanup var mapIDs = Object.keys(MAPS); mapIDs.forEach(function(mapId) { - var mapDivId = document.querySelector("[__pluginmapid='" + mapId + "']"); + var mapDivId = document.querySelector('[__pluginmapid=\'' + mapId + '\']'); if (!mapDivId) { if (MAPS[mapDivId]) { MAPS[mapDivId].destroy(); @@ -105,12 +104,12 @@ var CordovaGoogleMaps = { API_LOADED_STATUS = (window.google && window.google.maps) ? 2 : API_LOADED_STATUS; switch(API_LOADED_STATUS) { - case 0: - cordova.fireDocumentEvent('load_googlemaps', []); - break; - case 2: - pluginMap.trigger("googleready"); - break; + case 0: + cordova.fireDocumentEvent('load_googlemaps', []); + break; + case 2: + pluginMap.trigger('googleready'); + break; } }, removeMap: function(onSuccess, onError, args) { @@ -136,7 +135,7 @@ var CordovaGoogleMaps = { // memory cleanup var mapIDs = Object.keys(MAPS); mapIDs.forEach(function(mapId) { - var mapDivId = document.querySelector("[__pluginmapid='" + mapId + "']"); + var mapDivId = document.querySelector('[__pluginmapid=\'' + mapId + '\']'); if (!mapDivId) { if (MAPS[mapDivId]) { MAPS[mapDivId].destroy(); @@ -169,12 +168,12 @@ var CordovaGoogleMaps = { API_LOADED_STATUS = (window.google && window.google.maps) ? 2 : API_LOADED_STATUS; switch(API_LOADED_STATUS) { - case 0: - cordova.fireDocumentEvent('load_googlemaps', []); - break; - case 2: - pluginStreetView.trigger("googleready"); - break; + case 0: + cordova.fireDocumentEvent('load_googlemaps', []); + break; + case 2: + pluginStreetView.trigger('googleready'); + break; } }, }; diff --git a/src/browser/PluginCircle.js b/src/browser/PluginCircle.js index 0249da087..94684f7b9 100644 --- a/src/browser/PluginCircle.js +++ b/src/browser/PluginCircle.js @@ -3,13 +3,12 @@ var utils = require('cordova/utils'), event = require('cordova-plugin-googlemaps.event'), - BaseClass = require('cordova-plugin-googlemaps.BaseClass'), - LatLng = require('cordova-plugin-googlemaps.LatLng'); + BaseClass = require('cordova-plugin-googlemaps.BaseClass'); function PluginCircle(pluginMap) { var self = this; BaseClass.apply(self); - Object.defineProperty(self, "pluginMap", { + Object.defineProperty(self, 'pluginMap', { value: pluginMap, writable: false }); diff --git a/src/browser/PluginEnvironment.js b/src/browser/PluginEnvironment.js index 7d8c4f397..59327d48c 100644 --- a/src/browser/PluginEnvironment.js +++ b/src/browser/PluginEnvironment.js @@ -2,16 +2,16 @@ var envOptions = {}; module.exports = { - 'isAvailable': function(onSuccess, onError, args) { + 'isAvailable': function(onSuccess) { onSuccess(); }, - 'setBackGroundColor': function(onSuccess, onError, args) { + 'setBackGroundColor': function(onSuccess) { // stub onSuccess(); }, - 'getLicenseInfo': function(onSuccess, onError, args) { + 'getLicenseInfo': function(onSuccess) { // stub - onSuccess("cordova-plugin-googlemaps for browser does not need to display any open source lincenses. But for iOS, you still need to display the lincense."); + onSuccess('cordova-plugin-googlemaps for browser does not need to display any open source lincenses. But for iOS, you still need to display the lincense.'); }, 'setEnv': function(onSuccess, onError, args) { var options = args[0]; diff --git a/src/browser/PluginFusionTableOverlay.js b/src/browser/PluginFusionTableOverlay.js index ef55c39fd..d4d6064d6 100644 --- a/src/browser/PluginFusionTableOverlay.js +++ b/src/browser/PluginFusionTableOverlay.js @@ -1,83 +1,80 @@ var utils = require('cordova/utils'), - event = require('cordova-plugin-googlemaps.event'), - BaseClass = require('cordova-plugin-googlemaps.BaseClass'), - LatLng = require('cordova-plugin-googlemaps.LatLng'); + BaseClass = require('cordova-plugin-googlemaps.BaseClass'); function PluginFusionTableOverlay(pluginMap) { - var self = this; - BaseClass.apply(self); - Object.defineProperty(self, "pluginMap", { - value: pluginMap, - enumerable: false, - writable: false - }); + var self = this; + BaseClass.apply(self); + Object.defineProperty(self, 'pluginMap', { + value: pluginMap, + enumerable: false, + writable: false + }); } utils.extend(PluginFusionTableOverlay, BaseClass); PluginFusionTableOverlay.prototype._create = function(onSuccess, onError, args) { - var self = this, - map = self.pluginMap.get('map'), - hashCode = args[2], - fusionTableOverlayId = 'FusionTableOverlay_' + hashCode, - pluginOptions = args[1], - mapId = self.pluginMap.id; + var self = this, + map = self.pluginMap.get('map'), + hashCode = args[2], + fusionTableOverlayId = 'FusionTableOverlay_' + hashCode, + pluginOptions = args[1]; - var fusionTableOpts = { - 'map': map, - 'query': { - 'select': pluginOptions.select, - 'from': pluginOptions.from - } - }; - if (pluginOptions.where) { - fusionTableOpts.query.where = pluginOptions.where; - } - if (pluginOptions.orderBy) { - fusionTableOpts.query.orderBy = pluginOptions.orderBy; - } else if (pluginOptions.offset) { - fusionTableOpts.query.offset = pluginOptions.offset; - } - if (pluginOptions.limit) { - fusionTableOpts.query.limit = pluginOptions.limit; - } + var fusionTableOpts = { + 'map': map, + 'query': { + 'select': pluginOptions.select, + 'from': pluginOptions.from + } + }; + if (pluginOptions.where) { + fusionTableOpts.query.where = pluginOptions.where; + } + if (pluginOptions.orderBy) { + fusionTableOpts.query.orderBy = pluginOptions.orderBy; + } else if (pluginOptions.offset) { + fusionTableOpts.query.offset = pluginOptions.offset; + } + if (pluginOptions.limit) { + fusionTableOpts.query.limit = pluginOptions.limit; + } - var fusionTableOverlay = new google.maps.FusionTablesLayer(fusionTableOpts); + var fusionTableOverlay = new google.maps.FusionTablesLayer(fusionTableOpts); - self.pluginMap.objects[fusionTableOverlayId] = fusionTableOverlay; + self.pluginMap.objects[fusionTableOverlayId] = fusionTableOverlay; - onSuccess({ - 'id': fusionTableOverlayId - }); + onSuccess({ + 'id': fusionTableOverlayId + }); }; PluginFusionTableOverlay.prototype.setVisible = function(onSuccess, onError, args) { - var self = this, - map = self.pluginMap.get('map'), - overlayId = args[0], - fusionTableOverlay = self.pluginMap.objects[overlayId]; + var self = this, + map = self.pluginMap.get('map'), + overlayId = args[0], + fusionTableOverlay = self.pluginMap.objects[overlayId]; - if (fusionTableOverlay) { - FusionTableOverlay.setMap(args[1] ? map : null); - } - onSuccess(); + if (fusionTableOverlay) { + fusionTableOverlay.setMap(args[1] ? map : null); + } + onSuccess(); }; PluginFusionTableOverlay.prototype.remove = function(onSuccess, onError, args) { - var self = this; - var overlayId = args[0]; - var fusionTableOverlay = self.pluginMap.objects[overlayId]; - if (fusionTableOverlay) { - google.maps.event.clearInstanceListeners(fusionTableOverlay); - fusionTableOverlay.setMap(null); - fusionTableOverlay = undefined; - self.pluginMap.objects[overlayId] = undefined; - delete self.pluginMap.objects[overlayId]; - } - onSuccess(); + var self = this; + var overlayId = args[0]; + var fusionTableOverlay = self.pluginMap.objects[overlayId]; + if (fusionTableOverlay) { + google.maps.event.clearInstanceListeners(fusionTableOverlay); + fusionTableOverlay.setMap(null); + fusionTableOverlay = undefined; + self.pluginMap.objects[overlayId] = undefined; + delete self.pluginMap.objects[overlayId]; + } + onSuccess(); }; module.exports = PluginFusionTableOverlay; diff --git a/src/browser/PluginGeocoder.js b/src/browser/PluginGeocoder.js index aff062345..db8e835c7 100644 --- a/src/browser/PluginGeocoder.js +++ b/src/browser/PluginGeocoder.js @@ -1,13 +1,10 @@ -var utils = require('cordova/utils'); -var event = require('cordova-plugin-googlemaps.event'); var BaseArrayClass = require('cordova-plugin-googlemaps.BaseArrayClass'); var geocoder = null; var lastRequestTime = 0; var QUEUE = new BaseArrayClass(); -var totalCnt = 0; QUEUE.on('insert_at', function() { if (QUEUE.getLength() === 1) { this.trigger('next'); @@ -34,26 +31,26 @@ QUEUE.on('next', function() { var cmd = QUEUE.removeAt(0, true); geocoder.geocode(cmd.geocoderRequest, function(results, status) { switch(status) { - case google.maps.GeocoderStatus.ERROR: - cmd.onError('[geocoding] Cannot connect to Google servers'); - return; - case google.maps.GeocoderStatus.INVALID_REQUEST: - cmd.onError('[geocoding] Invalid request for geocoder'); - return; - case google.maps.GeocoderStatus.OVER_QUERY_LIMIT: - QUEUE.insertAt(0, cmd); - console.warn('[geocoding] Due to the OVER_QUERY_LIMIT error, wait 3 sec, then try again.'); - setTimeout(function() { - self._executing = false; - self.trigger('next'); - }, 3000 + Math.floor(Math.random() * 200)); - return; - case google.maps.GeocoderStatus.REQUEST_DENIED: - cmd.onError('[geocoding] Google denited your geocoding request.'); - return; - case google.maps.GeocoderStatus.UNKNOWN_ERROR: - cmd.onError('[geocoding] There was an unknown error. Please try again.'); - return; + case google.maps.GeocoderStatus.ERROR: + cmd.onError('[geocoding] Cannot connect to Google servers'); + return; + case google.maps.GeocoderStatus.INVALID_REQUEST: + cmd.onError('[geocoding] Invalid request for geocoder'); + return; + case google.maps.GeocoderStatus.OVER_QUERY_LIMIT: + QUEUE.insertAt(0, cmd); + console.warn('[geocoding] Due to the OVER_QUERY_LIMIT error, wait 3 sec, then try again.'); + setTimeout(function() { + self._executing = false; + self.trigger('next'); + }, 3000 + Math.floor(Math.random() * 200)); + return; + case google.maps.GeocoderStatus.REQUEST_DENIED: + cmd.onError('[geocoding] Google denited your geocoding request.'); + return; + case google.maps.GeocoderStatus.UNKNOWN_ERROR: + cmd.onError('[geocoding] There was an unknown error. Please try again.'); + return; } var pluginResults = results.map(function(geocoderResult) { @@ -78,56 +75,55 @@ QUEUE.on('next', function() { var administrative_area = []; var sublocality_area = []; - var idx; geocoderResult.address_components.forEach(function(addrComp) { result.extra.lines.push(addrComp.long_name); - if (!result.locality && addrComp.types.indexOf("locality") > -1) { + if (!result.locality && addrComp.types.indexOf('locality') > -1) { result.locality = addrComp.short_name; } - if (addrComp.types.indexOf("administrative_area_level_1") > -1 || - addrComp.types.indexOf("administrative_area_level_2") > -1 || - addrComp.types.indexOf("administrative_area_level_3") > -1 || - addrComp.types.indexOf("administrative_area_level_4") > -1) { + if (addrComp.types.indexOf('administrative_area_level_1') > -1 || + addrComp.types.indexOf('administrative_area_level_2') > -1 || + addrComp.types.indexOf('administrative_area_level_3') > -1 || + addrComp.types.indexOf('administrative_area_level_4') > -1) { addrComp.types.forEach(function(type) { - if (type.indexOf("administrative_area_level_") === 0) { - var idx = parseInt(type.replace("administrative_area_level_", ""), 10); + if (type.indexOf('administrative_area_level_') === 0) { + var idx = parseInt(type.replace('administrative_area_level_', ''), 10); administrative_area[idx - 1] = addrComp.long_name; } }); } - if (addrComp.types.indexOf("sublocality_level_1") > -1 || - addrComp.types.indexOf("sublocality_level_2") > -1 || - addrComp.types.indexOf("sublocality_level_3") > -1 || - addrComp.types.indexOf("sublocality_level_4") > -1 || - addrComp.types.indexOf("sublocality_level_5") > -1) { + if (addrComp.types.indexOf('sublocality_level_1') > -1 || + addrComp.types.indexOf('sublocality_level_2') > -1 || + addrComp.types.indexOf('sublocality_level_3') > -1 || + addrComp.types.indexOf('sublocality_level_4') > -1 || + addrComp.types.indexOf('sublocality_level_5') > -1) { addrComp.types.forEach(function(type) { - if (type.indexOf("sublocality_level_") === 0) { - var idx = parseInt(type.replace("sublocality_level_", ""), 10); + if (type.indexOf('sublocality_level_') === 0) { + var idx = parseInt(type.replace('sublocality_level_', ''), 10); sublocality_area[idx - 1] = addrComp.long_name; } }); } - if (!result.country && addrComp.types.indexOf("country") > -1) { + if (!result.country && addrComp.types.indexOf('country') > -1) { result.country = addrComp.long_name; result.countryCode = addrComp.short_name; } - if (!result.postalCode && addrComp.types.indexOf("postal_code") > -1) { + if (!result.postalCode && addrComp.types.indexOf('postal_code') > -1) { result.postalCode = addrComp.long_name; } - if (!result.postalCode && addrComp.types.indexOf("postal_code") > -1) { + if (!result.postalCode && addrComp.types.indexOf('postal_code') > -1) { result.postalCode = addrComp.long_name; } - if (!result.thoroughfare && addrComp.types.indexOf("street_address") > -1) { + if (!result.thoroughfare && addrComp.types.indexOf('street_address') > -1) { result.thoroughfare = addrComp.long_name; } }); if (administrative_area.length > 0) { result.adminArea = administrative_area.shift(); - result.subAdminArea = administrative_area.join(","); + result.subAdminArea = administrative_area.join(','); } if (sublocality_area.length > 0) { - result.subLocality = sublocality_area.join(","); + result.subLocality = sublocality_area.join(','); } //result.extra = geocoderResult.address_components; // for debug diff --git a/src/browser/PluginGroundOverlay.js b/src/browser/PluginGroundOverlay.js index 0fea91e11..fc3d96f56 100644 --- a/src/browser/PluginGroundOverlay.js +++ b/src/browser/PluginGroundOverlay.js @@ -10,7 +10,7 @@ var utils = require('cordova/utils'), function PluginGroundOverlay(pluginMap) { var self = this; BaseClass.apply(self); - Object.defineProperty(self, "pluginMap", { + Object.defineProperty(self, 'pluginMap', { value: pluginMap, writable: false }); @@ -198,14 +198,14 @@ function CustomGroundOverlay(url, bounds, options) { //------------------------------------------------------------ var img = new Image(); img.src = url; - img.style.position = "absolute"; - img.style.WebkitTransformOrigin = "50% 50%"; - img.style.MozTransformOrigin = "50% 50%"; - img.style.transformOrigin = "50% 50%"; - self.set("img", img); - - self.set("url", url); - self.addListener("url_changed", function() { + img.style.position = 'absolute'; + img.style.WebkitTransformOrigin = '50% 50%'; + img.style.MozTransformOrigin = '50% 50%'; + img.style.transformOrigin = '50% 50%'; + self.set('img', img); + + self.set('url', url); + self.addListener('url_changed', function() { img.src = self.get('url'); }); @@ -343,58 +343,57 @@ CustomGroundOverlay.prototype.setOpacity = function(opacity) { CustomGroundOverlay.prototype.setBearing = function(bearing) { var self = this; - self.set("bearing", bearing); + self.set('bearing', bearing); }; CustomGroundOverlay.prototype.setBounds = function(bounds) { var self = this; - self.set("bounds", bounds); + self.set('bounds', bounds); }; CustomGroundOverlay.prototype.setOpacity = function(opacity) { var self = this; - self.set("opacity", opacity); + self.set('opacity', opacity); }; CustomGroundOverlay.prototype.setZIndex = function(zIndex) { var self = this; - self.set("zIndex", zIndex); + self.set('zIndex', zIndex); }; CustomGroundOverlay.prototype.setVisible = function(visible) { var self = this; - self.set("visible", visible); + self.set('visible', visible); }; CustomGroundOverlay.prototype.setImage = function(url) { var self = this; - self.set("url", url); + self.set('url', url); }; CustomGroundOverlay.prototype.getBounds = function() { var self = this; return new google.maps.LatLngBounds( - self.get("sw"), self.get("ne") + self.get('sw'), self.get('ne') ); }; CustomGroundOverlay.prototype.draw = function() { - var self = this; + var self = this, projection = self.getProjection(); if (!projection) { return; } var bounds = self.get('bounds'), - center = bounds.getCenter(), - img = self.get("img"); + img = self.get('img'); // Calculate positions var swPx = projection.fromLatLngToDivPixel(bounds.getSouthWest()), nePx = projection.fromLatLngToDivPixel(bounds.getNorthEast()); - img.style.left = swPx.x + "px"; - img.style.top = nePx.y + "px"; - img.style.width = (nePx.x - swPx.x) + "px"; - img.style.height = (swPx.y - nePx.y) + "px"; + img.style.left = swPx.x + 'px'; + img.style.top = nePx.y + 'px'; + img.style.width = (nePx.x - swPx.x) + 'px'; + img.style.height = (swPx.y - nePx.y) + 'px'; img.style.transform = 'rotate(' + self.get('bearing') + 'deg)'; img.style.WebkitTransform = 'rotate(' + self.get('bearing') + 'deg)'; img.style.MozTransform = 'rotate(' + self.get('bearing') + 'deg)'; @@ -403,11 +402,11 @@ CustomGroundOverlay.prototype.draw = function() { CustomGroundOverlay.prototype.onAdd = function() { var self = this; self.set('mapPane', self.getPanes().mapPane); - self.getPanes().mapPane.appendChild(self.get("img")); + self.getPanes().mapPane.appendChild(self.get('img')); }; CustomGroundOverlay.prototype.onRemove = function() { var self = this; - self.get('mapPane').removeChild(self.get("img")); + self.get('mapPane').removeChild(self.get('img')); google.maps.event.clearInstanceListeners(self.get('img')); }; diff --git a/src/browser/PluginKmlOverlay.js b/src/browser/PluginKmlOverlay.js index c01fb2d3d..13c57243a 100644 --- a/src/browser/PluginKmlOverlay.js +++ b/src/browser/PluginKmlOverlay.js @@ -1,13 +1,12 @@ var InlineWorker = require('cordova-plugin-googlemaps.InlineWorker'); -function PluginKmlOverlay(pluginMap) { +function PluginKmlOverlay() { // stub } PluginKmlOverlay.prototype._create = function(onSuccess, onError, args) { - var self = this, - pluginOptions = args[1]; + var pluginOptions = args[1]; if (!/^https?:/.test(location.protocol)) { return onError('KmlOverlay is only available on http: or https: protocols.'); @@ -23,9 +22,9 @@ PluginKmlOverlay.prototype._create = function(onSuccess, onError, args) { onSuccess(evt.data); }; worker.onerror = onError; - var link = document.createElement("a"); + var link = document.createElement('a'); link.href = pluginOptions.url; - var url = link.protocol+"//"+link.host+link.pathname+link.search; + var url = link.protocol+'//'+link.host+link.pathname+link.search; worker.postMessage({ 'url': url }); @@ -38,14 +37,14 @@ function loadKml(self) { // code: https://stackoverflow.com/q/32912732/697856 var createCORSRequest = function(method, url, asynch) { var xhr = new XMLHttpRequest(); - if ("withCredentials" in xhr) { + if ('withCredentials' in xhr) { // XHR for Chrome/Firefox/Opera/Safari. xhr.open(method, url, asynch); // xhr.setRequestHeader('MEDIBOX', 'login'); xhr.setRequestHeader('Content-Type', 'application/xml; charset=UTF-8'); - } else if (typeof XDomainRequest != "undefined") { + } else if (typeof window.XDomainRequest != 'undefined') { // XDomainRequest for IE. - xhr = new XDomainRequest(); + xhr = new window.XDomainRequest(); xhr.open(method, url, asynch); } else { // CORS not supported. @@ -96,17 +95,17 @@ function loadKml(self) { */ var UNESCAPE = { - "&": "&", - "<": "<", - ">": ">", - "'": "'", - """: '"' + '&': '&', + '<': '<', + '>': '>', + ''': '\'', + '"': '"' }; - var CHILD_NODE_KEY = "#"; + var CHILD_NODE_KEY = '#'; function parseXML(text) { - var list = String.prototype.split.call(text, /<([^!<>?](?:'[\S\s]*?'|"[\S\s]*?"|[^'"<>])*|!(?:--[\S\s]*?--|\[[^\[\]'"<>]+\[[\S\s]*?]]|DOCTYPE[^\[<>]*?\[[\S\s]*?]|(?:ENTITY[^"<>]*?"[\S\s]*?")?[\S\s]*?)|\?[\S\s]*?\?)>/); + var list = String.prototype.split.call(text, /<([^!<>?](?:'[\S\s]*?'|"[\S\s]*?"|[^'"<>])*|!(?:--[\S\s]*?--|\[[^[]'"<>]+\[[\S\s]*?]]|DOCTYPE[^[<>]*?\[[\S\s]*?]|(?:ENTITY[^"<>]*?"[\S\s]*?")?[\S\s]*?)|\?[\S\s]*?\?)>/); var length = list.length; // root element @@ -131,9 +130,9 @@ function loadKml(self) { function parseNode(tag) { var tagLength = tag.length; var firstChar = tag[0]; - if (firstChar === "/") { + if (firstChar === '/') { // close tag - var closed = tag.replace(/^\/|[\s\/].*$/g, "").toLowerCase(); + var closed = tag.replace(/^\/|[\s/].*$/g, '').toLowerCase(); while (stack.length) { var tagName = elem.n && elem.n.toLowerCase(); elem = stack.pop(); @@ -142,18 +141,18 @@ function loadKml(self) { // } else if (firstChar === "?") { // // XML declaration // appendChild({n: "?", r: tag.substr(1, tagLength - 2)}); - } else if (firstChar === "!") { - if (tag.substr(1, 7) === "[CDATA[" && tag.substr(-2) === "]]") { + } else if (firstChar === '!') { + if (tag.substr(1, 7) === '[CDATA[' && tag.substr(-2) === ']]') { // CDATA section appendText(tag.substr(8, tagLength - 10)); } else { // comment - appendChild({n: "!", r: tag.substr(1)}); + appendChild({n: '!', r: tag.substr(1)}); } } else { var child = openTag(tag); appendChild(child); - if (tag[tagLength - 1] === "/") { + if (tag[tagLength - 1] === '/') { child.c = 1; // emptyTag } else { stack.push(elem); // openTag @@ -174,8 +173,8 @@ function loadKml(self) { function openTag(tag) { var elem = {f: []}; - tag = tag.replace(/\s*\/?$/, ""); - var pos = tag.search(/[\s='"\/]/); + tag = tag.replace(/\s*\/?$/, ''); + var pos = tag.search(/[\s='"/]/); if (pos < 0) { elem.n = tag; } else { @@ -195,20 +194,19 @@ function loadKml(self) { str = removeSpaces(str); if (!str) return; - var pos = str.indexOf("="); + var pos = str.indexOf('='); if (pos < 0) { // bare attribute - str = str; val = null; } else { // attribute key/value pair - val = str.substr(pos + 1).replace(/^\s+/, ""); - str = str.substr(0, pos).replace(/\s+$/, ""); + val = str.substr(pos + 1).replace(/^\s+/, ''); + str = str.substr(0, pos).replace(/\s+$/, ''); // quote: foo="FOO" bar='BAR' var firstChar = val[0]; var lastChar = val[val.length - 1]; - if (firstChar === lastChar && (firstChar === "'" || firstChar === '"')) { + if (firstChar === lastChar && (firstChar === '\'' || firstChar === '"')) { val = val.substr(1, val.length - 2); } @@ -224,13 +222,13 @@ function loadKml(self) { } function removeSpaces(str) { - return str && str.replace(/^\s+|\s+$/g, ""); + return str && str.replace(/^\s+|\s+$/g, ''); } function unescapeXML(str) { return str.replace(/(&(?:lt|gt|amp|apos|quot|#(?:\d{1,6}|x[0-9a-fA-F]{1,5}));)/g, function(str) { - if (str[1] === "#") { - var code = (str[2] === "x") ? parseInt(str.substr(3), 16) : parseInt(str.substr(2), 10); + if (str[1] === '#') { + var code = (str[2] === 'x') ? parseInt(str.substr(3), 16) : parseInt(str.substr(2), 10); if (code > -1) return String.fromCharCode(code); } return UNESCAPE[str] || str; @@ -257,7 +255,7 @@ function loadKml(self) { } object.tagName = elem.n; childList.forEach(function(child) { - if ("string" === typeof child) { + if ('string' === typeof child) { addObject(object, CHILD_NODE_KEY, child); } else { addObject(object, child.n, toObject(child, reviver)); @@ -266,7 +264,7 @@ function loadKml(self) { } else if (childLength) { // the node has single child node but no attribute var child = childList[0]; - if ("string" === typeof child) { + if ('string' === typeof child) { object = { 'tagName': elem.n, 'value': child, @@ -294,19 +292,19 @@ function loadKml(self) { } if (reviver) { - object = reviver(elem.n || "", object); + object = reviver(elem.n || '', object); } return object; } function addAttribute(object, key, val) { - if ("undefined" === typeof val) return; + if ('undefined' === typeof val) return; object.attributes = object.attributes || {}; object.attributes[key] = val; } function addObject(object, key, val) { - if ("undefined" === typeof val) return; + if ('undefined' === typeof val) return; object.value = object.value || {}; object.value.children = object.value.children || []; if (typeof val === 'object' && val.tagName) { @@ -321,10 +319,10 @@ function loadKml(self) { } return function(text, reviver) { - text = text.replace(/<\?xml[^>]+>/i, ""); + text = text.replace(/<\?xml[^>]+>/i, ''); var xmlTree = parseXML(text); var result = toObject(xmlTree, reviver); - result.tagName = "document"; + result.tagName = 'document'; return result; }; })(); @@ -378,7 +376,7 @@ function loadKml(self) { // Generate a style id for the tag var styleId = rootElement.attributes ? rootElement.attributes.id : null; if (!styleId) { - styleId = "__" + Math.floor(Date.now() * Math.random()) + "__"; + styleId = '__' + Math.floor(Date.now() * Math.random()) + '__'; } var result = { 'styleId': styleId @@ -411,12 +409,12 @@ function loadKml(self) { // Generate a schema id for the tag var schemaId = rootElement.attributes ? rootElement.attributes.id : null; if (!schemaId) { - schemaId = "__" + Math.floor(Date.now() * Math.random()) + "__"; + schemaId = '__' + Math.floor(Date.now() * Math.random()) + '__'; } // Store schema information into the schemaHolder. var schema = {}; - schema.name = rootElement.attributes ? rootElement.attributes.id : "__" + Math.floor(Date.now() * Math.random()) + "__"; + schema.name = rootElement.attributes ? rootElement.attributes.id : '__' + Math.floor(Date.now() * Math.random()) + '__'; if (rootElement.value.children) { var children = []; rootElement.value.children.forEach(function(childNode) { @@ -435,19 +433,18 @@ function loadKml(self) { }; KmlParserClass.prototype._coordinates = function(rootElement) { - var _parser = this; var result = {}; var latLngList = []; var txt = rootElement.value; - txt = txt.replace(/\s+/g, "\n"); - txt = txt.replace(/\n+/g, "\n"); + txt = txt.replace(/\s+/g, '\n'); + txt = txt.replace(/\n+/g, '\n'); var lines = txt.split(/\n/); lines.forEach(function(line) { - line = line.replace(/[^0-9,.\\-]/g, ""); - if (line !== "") { - var tmpArry = line.split(","); + line = line.replace(/[^0-9,.\\-]/g, ''); + if (line !== '') { + var tmpArry = line.split(','); latLngList.push({ 'lat': parseFloat(tmpArry[1]), 'lng': parseFloat(tmpArry[0]) @@ -483,7 +480,7 @@ function loadKml(self) { var value = rootElement.value; if (/^-?[0-9]+$/.test(value)) { result.value = parseInt(value, 10); - } else if (/^-?[0-9\.]+$/.test(value)) { + } else if (/^-?[0-9.]+$/.test(value)) { result.value = parseFloat(value, 10); } else { result.value = value; @@ -520,21 +517,21 @@ function loadKml(self) { xhr.send(); } })) - .then(function(xmlTxt) { + .then(function(xmlTxt) { //----------------- // Parse it //----------------- - var doc = fromXML(xmlTxt); - var parser = new KmlParserClass(); - var root = parser.parseXml(doc); - - var result = { - 'schemas': parser.schemaHolder, - 'styles': parser.styleHolder, - 'root': root - }; - postMessage(result); - }); + var doc = fromXML(xmlTxt); + var parser = new KmlParserClass(); + var root = parser.parseXml(doc); + + var result = { + 'schemas': parser.schemaHolder, + 'styles': parser.styleHolder, + 'root': root + }; + postMessage(result); + }); }; } diff --git a/src/browser/PluginLocationService.js b/src/browser/PluginLocationService.js index d5c33f8df..3d078196c 100644 --- a/src/browser/PluginLocationService.js +++ b/src/browser/PluginLocationService.js @@ -1,9 +1,4 @@ - -var utils = require('cordova/utils'); -var event = require('cordova-plugin-googlemaps.event'); -var BaseClass = require('cordova-plugin-googlemaps.BaseClass'); - var LOCATION_ERROR = { '1': 'service_denied', '2': 'not_available', @@ -11,7 +6,7 @@ var LOCATION_ERROR = { }; module.exports = { - 'hasPermission': function(onSuccess, onError, args) { + 'hasPermission': function(onSuccess, onError) { if (navigator.permissions) { navigator.permissions.query({'name': 'geolocation'}) .then(function(permission) { @@ -22,7 +17,7 @@ module.exports = { onError('Browser does not support this feature.'); } }, - 'getMyLocation': function(onSuccess, onError, args) { + 'getMyLocation': function(onSuccess, onError) { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { diff --git a/src/browser/PluginMap.js b/src/browser/PluginMap.js index 35b849346..b4c5d69a3 100644 --- a/src/browser/PluginMap.js +++ b/src/browser/PluginMap.js @@ -7,12 +7,12 @@ var utils = require('cordova/utils'), MapTypeId = require('cordova-plugin-googlemaps.MapTypeId'); var MAP_TYPES = {}; -MAP_TYPES[MapTypeId.NORMAL] = "roadmap"; -MAP_TYPES[MapTypeId.ROADMAP] = "roadmap"; -MAP_TYPES[MapTypeId.SATELLITE] = "satellite"; -MAP_TYPES[MapTypeId.HYBRID] = "hybrid"; -MAP_TYPES[MapTypeId.TERRAIN] = "terrain"; -MAP_TYPES[MapTypeId.NONE] = "none"; +MAP_TYPES[MapTypeId.NORMAL] = 'roadmap'; +MAP_TYPES[MapTypeId.ROADMAP] = 'roadmap'; +MAP_TYPES[MapTypeId.SATELLITE] = 'satellite'; +MAP_TYPES[MapTypeId.HYBRID] = 'hybrid'; +MAP_TYPES[MapTypeId.TERRAIN] = 'terrain'; +MAP_TYPES[MapTypeId.NONE] = 'none'; var LOCATION_ERROR = {}; LOCATION_ERROR[1] = 'service_denied'; @@ -34,54 +34,54 @@ function displayGrayMap(container) { '

Can not display map.
Check the developer console.

', '', '' - ].join("\n"); + ].join('\n'); } } -function PluginMap(mapId, options, mapDivId) { +function PluginMap(mapId, options) { var self = this; BaseClass.apply(this); - var mapDiv = document.querySelector("[__pluginMapId='" + mapId + "']"); + var mapDiv = document.querySelector('[__pluginMapId=\'' + mapId + '\']'); mapDiv.style.backgroundColor = 'rgb(229, 227, 223)'; - var container = document.createElement("div"); - container.style.userSelect="none"; - container.style["-webkit-user-select"]="none"; - container.style["-moz-user-select"]="none"; - container.style["-ms-user-select"]="none"; - mapDiv.style.position = "relative"; - container.style.position = "absolute"; + var container = document.createElement('div'); + container.style.userSelect='none'; + container.style['-webkit-user-select']='none'; + container.style['-moz-user-select']='none'; + container.style['-ms-user-select']='none'; + mapDiv.style.position = 'relative'; + container.style.position = 'absolute'; container.style.top = 0; container.style.bottom = 0; container.style.right = 0; container.style.left = 0; mapDiv.insertBefore(container, mapDiv.firstElementChild); - self.set("isGoogleReady", false); - self.set("container", container); + self.set('isGoogleReady', false); + self.set('container', container); self.PLUGINS = {}; - Object.defineProperty(self, "id", { + Object.defineProperty(self, 'id', { value: mapId, writable: false }); - Object.defineProperty(self, "objects", { + Object.defineProperty(self, 'objects', { value: {}, writable: false }); - Object.defineProperty(self, "activeMarker", { + Object.defineProperty(self, 'activeMarker', { value: null, writable: true }); self.set('clickable', true); - self.one("googleready", function() { - self.set("isGoogleReady", true); + self.one('googleready', function() { + self.set('isGoogleReady', true); var mapTypeReg = new google.maps.MapTypeRegistry(); mapTypeReg.set('none', new google.maps.ImageMapType({ - 'getTileUrl': function(point, zoom) { return null; }, + 'getTileUrl': function() { return null; }, 'name': 'none_type', 'tileSize': new google.maps.Size(256, 256), 'minZoom': 0, @@ -142,7 +142,7 @@ function PluginMap(mapId, options, mapDivId) { displayGrayMap(mapDiv); }, 3000); - map.addListener("bounds_changed", function() { + map.addListener('bounds_changed', function() { var boundsLimit = map.get('boundsLimit'); if (!boundsLimit) { return; @@ -182,34 +182,34 @@ function PluginMap(mapId, options, mapDivId) { map.panTo(dummyLatLng); }); - google.maps.event.addListenerOnce(map, "projection_changed", function() { + google.maps.event.addListenerOnce(map, 'projection_changed', function() { clearTimeout(timeoutError); self.trigger(event.MAP_READY); - map.addListener("idle", self._onCameraEvent.bind(self, 'camera_move_end')); + map.addListener('idle', self._onCameraEvent.bind(self, 'camera_move_end')); //map.addListener("bounce_changed", self._onCameraEvent.bind(self, 'camera_move')); - map.addListener("drag", self._onCameraEvent.bind(self, event.CAMERA_MOVE)); - map.addListener("dragend", self._onCameraEvent.bind(self, event.CAMERA_MOVE_END)); - map.addListener("dragstart", self._onCameraEvent.bind(self, event.CAMERA_MOVE_START)); + map.addListener('drag', self._onCameraEvent.bind(self, event.CAMERA_MOVE)); + map.addListener('dragend', self._onCameraEvent.bind(self, event.CAMERA_MOVE_END)); + map.addListener('dragstart', self._onCameraEvent.bind(self, event.CAMERA_MOVE_START)); - map.addListener("click", function(evt) { + map.addListener('click', function(evt) { self._onMapEvent.call(self, event.MAP_CLICK, evt); }); - map.addListener("mousedown", function(evt) { + map.addListener('mousedown', function() { map.set('mousedown_time', Date.now()); }); - map.addListener("mouseup", function(evt) { + map.addListener('mouseup', function(evt) { if (Date.now() - (map.get('mousedown_time') || Date.now()) > 500) { self._onMapEvent.call(self, event.MAP_LONG_CLICK, evt); } }); - map.addListener("drag", function(evt) { + map.addListener('drag', function(evt) { self._onMapEvent.call(self, event.MAP_DRAG, evt); }); - map.addListener("dragend", function(evt) { + map.addListener('dragend', function(evt) { self._onMapEvent.call(self, event.MAP_DRAG_END, evt); }); - map.addListener("dragstart", function(evt) { + map.addListener('dragstart', function(evt) { map.set('mousedown_time', undefined); self._onMapEvent.call(self, event.MAP_DRAG_START, evt); }); @@ -253,7 +253,7 @@ utils.extend(PluginMap, BaseClass); PluginMap.prototype.setOptions = function(onSuccess, onError, args) { var self = this; - var map = self.get("map"), + var map = self.get('map'), options = args[0]; var mapInitOptions = {}; @@ -333,12 +333,12 @@ PluginMap.prototype.setActiveMarkerId = function(onSuccess, onError, args) { self.activeMarker = self.objects[markerId]; onSuccess(); }; -PluginMap.prototype.clear = function(onSuccess, onError, args) { - self.activeMarker = null; +PluginMap.prototype.clear = function(onSuccess) { + this.activeMarker = null; onSuccess(); }; -PluginMap.prototype.getFocusedBuilding = function(onSuccess, onError, args) { +PluginMap.prototype.getFocusedBuilding = function(onSuccess) { // stub onSuccess(-1); }; @@ -350,38 +350,38 @@ PluginMap.prototype.setDiv = function(onSuccess, onError, args) { if (args.length === 0) { if (container && container.parentNode) { - container.parentNode.removeAttribute("__pluginMapId"); + container.parentNode.removeAttribute('__pluginMapId'); container.parentNode.removeChild(container); } } else { var domId = args[0]; - var mapDiv = document.querySelector("[__pluginDomId='" + domId + "']"); - mapDiv.style.position = "relative"; + var mapDiv = document.querySelector('[__pluginDomId=\'' + domId + '\']'); + mapDiv.style.position = 'relative'; mapDiv.insertBefore(container, mapDiv.firstElementChild); - mapDiv.setAttribute("__pluginMapId", self.id); + mapDiv.setAttribute('__pluginMapId', self.id); } - google.maps.event.trigger(map, "resize"); + google.maps.event.trigger(map, 'resize'); onSuccess(); }; -PluginMap.prototype.resizeMap = function(onSuccess, onError, args) { +PluginMap.prototype.resizeMap = function(onSuccess) { var self = this; - var map = self.get("map"); + var map = self.get('map'); - google.maps.event.trigger(map, "resize"); + google.maps.event.trigger(map, 'resize'); onSuccess(); }; PluginMap.prototype.panBy = function(onSuccess, onError, args) { var self = this; - var map = self.get("map"); + var map = self.get('map'); map.panBy.apply(map, args); onSuccess(); }; PluginMap.prototype.setCameraBearing = function(onSuccess, onError, args) { var self = this; - var map = self.get("map"); + var map = self.get('map'); var heading = args[0]; map.setHeading(heading); @@ -390,7 +390,7 @@ PluginMap.prototype.setCameraBearing = function(onSuccess, onError, args) { PluginMap.prototype.setCameraZoom = function(onSuccess, onError, args) { var self = this; - var map = self.get("map"); + var map = self.get('map'); var zoom = args[0]; map.setZoom(zoom); @@ -399,9 +399,9 @@ PluginMap.prototype.setCameraZoom = function(onSuccess, onError, args) { PluginMap.prototype.setCameraTarget = function(onSuccess, onError, args) { var self = this; - var map = self.get("map"); + var map = self.get('map'); var lat = args[0], - lng = args[1]; + lng = args[1]; map.setCenter(new google.maps.LatLng(lat, lng)); onSuccess(); @@ -409,20 +409,20 @@ PluginMap.prototype.setCameraTarget = function(onSuccess, onError, args) { PluginMap.prototype.setCameraTilt = function(onSuccess, onError, args) { var self = this; - var map = self.get("map"); + var map = self.get('map'); var tilt = args[0]; - map.setTilt(); + map.setTilt(tilt); onSuccess(); }; -PluginMap.prototype.setMyLocationEnabled = function(onSuccess, onError, args) { +PluginMap.prototype.setMyLocationEnabled = function(onSuccess) { // stub onSuccess(); }; PluginMap.prototype.animateCamera = function(onSuccess, onError, args) { var self = this; - var map = self.get("map"); + var map = self.get('map'); var options = args[0]; var padding = 'padding' in options ? options.padding : 5; @@ -452,7 +452,7 @@ PluginMap.prototype.animateCamera = function(onSuccess, onError, args) { PluginMap.prototype.moveCamera = function(onSuccess, onError, args) { var self = this; - var map = self.get("map"); + var map = self.get('map'); var options = args[0]; var padding = 'padding' in options ? options.padding : 5; @@ -479,21 +479,20 @@ PluginMap.prototype.moveCamera = function(onSuccess, onError, args) { }; PluginMap.prototype.setMapTypeId = function(onSuccess, onError, args) { var self = this; - var map = self.get("map"); + var map = self.get('map'); var mapTypeId = args[0]; map.setMapTypeId(MAP_TYPES[mapTypeId]); onSuccess(); }; PluginMap.prototype.setClickable = function(onSuccess, onError, args) { var self = this; - var map = self.get("map"); var clickable = args[0]; self.set('clickable', clickable); onSuccess(); }; PluginMap.prototype.setVisible = function(onSuccess, onError, args) { var self = this; - var map = self.get("map"); + var map = self.get('map'); var visibility = args[0]; var mapDiv = map.getDiv(); if (mapDiv) { @@ -502,13 +501,13 @@ PluginMap.prototype.setVisible = function(onSuccess, onError, args) { onSuccess(); }; -PluginMap.prototype.setPadding = function(onSuccess, onError, args) { +PluginMap.prototype.setPadding = function(onSuccess) { // stub onSuccess(); }; PluginMap.prototype.setAllGesturesEnabled = function(onSuccess, onError, args) { var self = this; - var map = self.get("map"); + var map = self.get('map'); var enabled = args[0]; map.setOptions({ gestureHandling: enabled === true ? 'auto': 'none' @@ -518,7 +517,7 @@ PluginMap.prototype.setAllGesturesEnabled = function(onSuccess, onError, args) { }; PluginMap.prototype.setCompassEnabled = function(onSuccess, onError, args) { var self = this; - var map = self.get("map"); + var map = self.get('map'); var enabled = args[0]; map.setOptions({ rotateControl: enabled === true @@ -532,7 +531,7 @@ PluginMap.prototype.setCompassEnabled = function(onSuccess, onError, args) { }; PluginMap.prototype.setTrafficEnabled = function(onSuccess, onError, args) { var self = this; - var map = self.get("map"); + var map = self.get('map'); var enabled = args[0]; var trafficLayer = map.get('trafficLayer'); @@ -554,7 +553,7 @@ PluginMap.prototype.setTrafficEnabled = function(onSuccess, onError, args) { PluginMap.prototype.fromLatLngToPoint = function(onSuccess, onError, args) { var self = this; - var map = self.get("map"); + var map = self.get('map'); var lat = args[0], lng = args[1]; @@ -563,10 +562,8 @@ PluginMap.prototype.fromLatLngToPoint = function(onSuccess, onError, args) { ne = bounds.getNorthEast(), sw = bounds.getSouthWest(), zoom = map.getZoom(), - south = sw.lat(), north = ne.lat(), - west = sw.lng(), - east = ne.lng(); + west = sw.lng(); var nowrapFlag = !bounds.contains(new google.maps.LatLng(north, 179)); @@ -578,7 +575,7 @@ PluginMap.prototype.fromLatLngToPoint = function(onSuccess, onError, args) { PluginMap.prototype.fromPointToLatLng = function(onSuccess, onError, args) { var self = this; - var map = self.get("map"); + var map = self.get('map'); var x = args[0], y = args[1]; @@ -597,12 +594,12 @@ PluginMap.prototype.fromPointToLatLng = function(onSuccess, onError, args) { }; -PluginMap.prototype.setIndoorEnabled = function(onSuccess, onError, args) { +PluginMap.prototype.setIndoorEnabled = function(onSuccess) { // stub onSuccess(); }; -PluginMap.prototype.toDataURL = function(onSuccess, onError, args) { +PluginMap.prototype.toDataURL = function(onSuccess) { // stub onSuccess(); }; @@ -628,8 +625,7 @@ PluginMap.prototype._syncInfoWndPosition = function() { }; PluginMap.prototype._onMapEvent = function(evtName, evt) { - var self = this, - map = self.get("map"); + var self = this; if (self.get('clickable') === false && (evtName === event.MAP_CLICK || evtName === event.MAP_LONG_CLICK)) { @@ -667,7 +663,7 @@ PluginMap.prototype._onMapEvent = function(evtName, evt) { PluginMap.prototype._onCameraEvent = function(evtName) { var self = this, - map = self.get("map"), + map = self.get('map'), center = map.getCenter(), bounds = map.getBounds(), ne = bounds.getNorthEast(), @@ -698,7 +694,6 @@ PluginMap.prototype._onCameraEvent = function(evtName) { PluginMap.prototype.loadPlugin = function(onSuccess, onError, args) { var self = this; - var map = self.get("map"); var className = args[0]; var plugin; diff --git a/src/browser/PluginMarker.js b/src/browser/PluginMarker.js index c4f61395d..697935373 100644 --- a/src/browser/PluginMarker.js +++ b/src/browser/PluginMarker.js @@ -7,11 +7,11 @@ var utils = require('cordova/utils'), function PluginMarker(pluginMap) { var self = this; BaseClass.apply(self); - Object.defineProperty(self, "pluginMap", { + Object.defineProperty(self, 'pluginMap', { value: pluginMap, writable: false }); - Object.defineProperty(self, "infoWnd", { + Object.defineProperty(self, 'infoWnd', { value: null, writable: true }); @@ -21,15 +21,16 @@ utils.extend(PluginMarker, BaseClass); PluginMarker.prototype._create = function(onSuccess, onError, args) { var self = this, - map = self.pluginMap.get('map'), markerId = 'marker_' + args[2], pluginOptions = args[1]; self.__create.call(self, markerId, pluginOptions, function(marker, properties) { onSuccess(properties); - }); + }, onError); }; -PluginMarker.prototype.__create = function(markerId, pluginOptions, onSuccess) { +/*eslint-disable no-unused-vars*/ +PluginMarker.prototype.__create = function(markerId, pluginOptions, onSuccess, onError) { +/*eslint-enable no-unused-vars*/ var self = this, map = self.pluginMap.get('map'); var markerOpts = { @@ -143,14 +144,15 @@ PluginMarker.prototype.__create = function(markerId, pluginOptions, onSuccess) { 'height': img.height }); }; - img.onerror = function() { + img.onerror = function(error) { + console.warn(error.getMessage()); onSuccess(marker, { 'id': markerId, 'width': 20, 'height': 42 }); }; - if (typeof markerOpts.icon === "string") { + if (typeof markerOpts.icon === 'string') { img.src = markerOpts.icon; } else { img.src = markerOpts.icon.url; @@ -238,19 +240,17 @@ PluginMarker.prototype.setInfoWindowAnchor = function(onSuccess, onError, args) var overlayId = args[0]; var marker = self.pluginMap.objects[overlayId]; if (marker) { - (new Promise(function(resolve, reject) { - var icon = marker.getIcon(); - var anchorX = args[1]; - anchorX = anchorX - icon.size.width / 2; - var anchorY = args[2]; - anchorY = anchorY - icon.size.height / 2; - marker.setOptions({ - 'anchorPoint': new google.maps.Point(anchorX, anchorY) - }); - if (self.infoWnd) { - self._showInfoWindow.call(self, marker); - } - })); + var icon = marker.getIcon(); + var anchorX = args[1]; + anchorX = anchorX - icon.size.width / 2; + var anchorY = args[2]; + anchorY = anchorY - icon.size.height / 2; + marker.setOptions({ + 'anchorPoint': new google.maps.Point(anchorX, anchorY) + }); + if (self.infoWnd) { + self._showInfoWindow.call(self, marker); + } } onSuccess(); }; @@ -295,7 +295,7 @@ PluginMarker.prototype.setIconAnchor = function(onSuccess, onError, args) { var marker = self.pluginMap.objects[overlayId]; if (marker) { var icon = marker.getIcon(); - if (typeof icon === "string") { + if (typeof icon === 'string') { icon = { 'url': icon }; @@ -328,9 +328,8 @@ PluginMarker.prototype.showInfoWindow = function(onSuccess, onError, args) { } onSuccess(); }; -PluginMarker.prototype.hideInfoWindow = function(onSuccess, onError, args) { +PluginMarker.prototype.hideInfoWindow = function(onSuccess) { var self = this; - var overlayId = args[0]; if (self.infoWnd) { google.maps.event.trigger(self.infoWnd, 'closeclick'); self.infoWnd.close(); @@ -348,8 +347,7 @@ PluginMarker.prototype.setIcon = function(onSuccess, onError, args) { .catch(onError); }; PluginMarker.prototype.setIcon_ = function(marker, iconOpts) { - var self = this; - return new Promise(function(resolve, reject) { + return new Promise(function(resolve) { if (marker) { if (Array.isArray(iconOpts)) { // Specifies color name or rule @@ -361,9 +359,9 @@ PluginMarker.prototype.setIcon_ = function(marker, iconOpts) { 'strokeWeight': 0, 'anchor': new google.maps.Point(12, 27) }; - } else if (typeof iconOpts === "object") { + } else if (typeof iconOpts === 'object') { - if (typeof iconOpts.size === "object") { + if (typeof iconOpts.size === 'object') { iconOpts.size = new google.maps.Size(iconOpts.size.width, iconOpts.size.height, 'px', 'px'); iconOpts.scaledSize = iconOpts.size; } @@ -432,11 +430,11 @@ PluginMarker.prototype._showInfoWindow = function(marker) { self.pluginMap._syncInfoWndPosition.call(self); var maxWidth = marker.getMap().getDiv().offsetWidth * 0.7; var html = []; - if (marker.get("title")) { - html.push(marker.get("title")); + if (marker.get('title')) { + html.push(marker.get('title')); } - if (marker.get("snippet")) { - html.push('' + marker.get("snippet") + ''); + if (marker.get('snippet')) { + html.push('' + marker.get('snippet') + ''); } if (html.length > 0) { container.innerHTML = html.join('
'); @@ -466,7 +464,7 @@ PluginMarker.prototype._showInfoWindow = function(marker) { PluginMarker.prototype.onMarkerClickEvent = function(evtName, marker) { var self = this; - var overlayId = marker.get("overlayId"); + var overlayId = marker.get('overlayId'); if (self.pluginMap.activeMarker && self.pluginMap.activeMarker !== marker) { self.onMarkerEvent(event.INFO_CLOSE, self.pluginMap.activeMarker); @@ -475,7 +473,7 @@ PluginMarker.prototype.onMarkerClickEvent = function(evtName, marker) { if (marker.get('disableAutoPan') === false) { self.pluginMap.get('map').panTo(marker.getPosition()); } - if (overlayId.indexOf("markercluster_") > -1) { + if (overlayId.indexOf('markercluster_') > -1) { self.onClusterEvent(evtName, marker); } else { self.onMarkerEvent(evtName, marker); diff --git a/src/browser/PluginMarkerCluster.js b/src/browser/PluginMarkerCluster.js index 59bb7235b..a7f9c4e3c 100644 --- a/src/browser/PluginMarkerCluster.js +++ b/src/browser/PluginMarkerCluster.js @@ -1,6 +1,3 @@ - - - var utils = require('cordova/utils'), event = require('cordova-plugin-googlemaps.event'), PluginMarker = require('cordova-plugin-googlemaps.PluginMarker'), @@ -18,17 +15,17 @@ function PluginMarkerCluster(pluginMap) { var self = this; PluginMarker.call(self, pluginMap); - Object.defineProperty(self, "pluginMarkers", { + Object.defineProperty(self, 'pluginMarkers', { value: {}, writable: false }); - Object.defineProperty(self, "debugFlags", { + Object.defineProperty(self, 'debugFlags', { value: {}, writable: false }); var deleteMarkers = new BaseArrayClass(); - Object.defineProperty(self, "deleteMarkers", { + Object.defineProperty(self, 'deleteMarkers', { value: deleteMarkers, writable: false }); @@ -41,11 +38,11 @@ function PluginMarkerCluster(pluginMap) { } self.pluginMap.objects[key] = undefined; - self.pluginMap.objects["marker_property_" + key] = undefined; + self.pluginMap.objects['marker_property_' + key] = undefined; self.pluginMarkers[key] = undefined; delete self.pluginMap.objects[key]; - delete self.pluginMap.objects["marker_property_" + key]; + delete self.pluginMap.objects['marker_property_' + key]; delete self.pluginMarkers[key]; self.pluginMarkers[key] = STATUS.DELETED; }); @@ -73,7 +70,7 @@ PluginMarkerCluster.prototype._create = function(onSuccess, onError, args) { var GEOCELL_GRID_SIZE = 4; - var GEOCELL_ALPHABET = "0123456789abcdef"; + var GEOCELL_ALPHABET = '0123456789abcdef'; function getGeocell(lat, lng, resolution) { var north = 90.0, @@ -97,7 +94,7 @@ PluginMarkerCluster.prototype._create = function(onSuccess, onError, args) { west += subcell_lng_span * x; east = west + subcell_lng_span; } - return cell.join(""); + return cell.join(''); } function _subdiv_char(posX, posY) { return GEOCELL_ALPHABET.charAt( @@ -129,7 +126,7 @@ PluginMarkerCluster.prototype._create = function(onSuccess, onError, args) { Promise.all(tasks) .then(function(results) { - var id = "markerclister_" + hashCode; + var id = 'markerclister_' + hashCode; self.debugFlags[id] = params.debug; var result = { @@ -160,12 +157,10 @@ PluginMarkerCluster.prototype.redrawClusters = function(onSuccess, onError, args //--------------------------- // Determine new or update //--------------------------- - var new_or_updateCnt = params.new_or_update.length; - - params.new_or_update.forEach(function(clusterData, i) { + params.new_or_update.forEach(function(clusterData) { var positionJSON = clusterData.position, markerId = clusterData.__pgmId, - clusterId_markerId = clusterId + "-" + markerId; + clusterId_markerId = clusterId + '-' + markerId; // Save the marker properties self.pluginMap.objects['marker_property_' + clusterId_markerId] = clusterData; @@ -187,12 +182,11 @@ PluginMarkerCluster.prototype.redrawClusters = function(onSuccess, onError, args if ('icon' in clusterData) { var iconObj = clusterData.icon, iconProperties = {}, - icon, label; - if (typeof iconObj === "string") { + if (typeof iconObj === 'string') { iconProperties.url = iconObj; properties.icon = iconProperties; - } else if (typeof iconObj === "object") { + } else if (typeof iconObj === 'object') { iconProperties = iconObj; if (clusterData.isClusterIcon) { if (iconObj.label) { @@ -241,9 +235,9 @@ PluginMarkerCluster.prototype.redrawClusters = function(onSuccess, onError, args // new or update //--------------- var tasks = []; - updateClusterIDs.forEach(function(clusterId_markerId, currentCnt) { + updateClusterIDs.forEach(function(clusterId_markerId) { self.pluginMarkers[clusterId_markerId] = STATUS.WORKING; - isNew = !(clusterId_markerId in self.pluginMap.objects); + var isNew = !(clusterId_markerId in self.pluginMap.objects); // Get the marker properties var markerProperties = changeProperties[clusterId_markerId], @@ -254,9 +248,9 @@ PluginMarkerCluster.prototype.redrawClusters = function(onSuccess, onError, args // regular marker //------------------- if (isNew) { - properties = self.pluginMap.objects["marker_property_" + clusterId_markerId]; + properties = self.pluginMap.objects['marker_property_' + clusterId_markerId]; - tasks.push(new Promise(function(resolve, reject) { + tasks.push(new Promise(function(resolve) { self.__create.call(self, clusterId_markerId, { 'position': properties.position, @@ -275,7 +269,7 @@ PluginMarkerCluster.prototype.redrawClusters = function(onSuccess, onError, args resolve(); } else { self.pluginMarkers[clusterId_markerId] = STATUS.CREATED; - allResults[clusterId_markerId.split("-")[1]] = { + allResults[clusterId_markerId.split('-')[1]] = { 'width': properties.width, 'height': properties.height }; @@ -310,15 +304,15 @@ PluginMarkerCluster.prototype.redrawClusters = function(onSuccess, onError, args if (isNew) { // If the requested id is new location, create a marker marker = newClusterIcon({ - 'map': map, - 'position': { - 'lat': markerProperties.lat, - 'lng': markerProperties.lng - }, - 'overlayId': clusterId_markerId, - 'opacity': 0 - }); - marker.addListener('click', self.onClusterEvent.bind(self, "cluster_click", marker)); + 'map': map, + 'position': { + 'lat': markerProperties.lat, + 'lng': markerProperties.lng + }, + 'overlayId': clusterId_markerId, + 'opacity': 0 + }); + marker.addListener('click', self.onClusterEvent.bind(self, 'cluster_click', marker)); // Store the marker instance with markerId self.pluginMap.objects[clusterId_markerId] = marker; @@ -338,7 +332,7 @@ PluginMarkerCluster.prototype.redrawClusters = function(onSuccess, onError, args if (markerProperties.icon) { var icon = markerProperties.icon; - tasks.push(new Promise(function(resolve, reject) { + tasks.push(new Promise(function(resolve) { self.setIconToClusterMarker.call(self, clusterId_markerId, marker, icon) .then(function() { @@ -358,7 +352,7 @@ PluginMarkerCluster.prototype.redrawClusters = function(onSuccess, onError, args } self.pluginMarkers[clusterId_markerId] = STATUS.DELETED; - console.error(errorMsg); + console.warn(error.getMessage()); self.deleteMarkers.push(clusterId_markerId); resolve(); }); @@ -386,7 +380,7 @@ PluginMarkerCluster.prototype.deleteProcess = function(clusterId, params) { return; } params.delete.forEach(function(key) { - self.deleteMarkers.push(clusterId + "-" + key); + self.deleteMarkers.push(clusterId + '-' + key); }); }; @@ -397,26 +391,26 @@ PluginMarkerCluster.prototype.setIconToClusterMarker = function(markerId, marker if (self.pluginMarkers[markerId] === STATUS.DELETED) { self._removeMarker.call(self, marker); delete self.pluginMap.objects[markerId]; - delete self.pluginMap.objects["marker_property_" + markerId]; + delete self.pluginMap.objects['marker_property_' + markerId]; delete self.pluginMarkers[markerId]; - reject("marker has been removed"); + reject('marker has been removed'); return; } self.setIcon_.call(self, marker, iconProperty) - .then(function() { - if (self.pluginMarkers[markerId] === STATUS.DELETED) { - self._removeMarker.call(self, marker); - delete pluginMap.objects[markerId]; - delete pluginMap.objects["marker_property_" + markerId]; - pluginMarkers.remove(markerId); + .then(function() { + if (self.pluginMarkers[markerId] === STATUS.DELETED) { + self._removeMarker.call(self, marker); + delete self.pluginMap.objects[markerId]; + delete self.pluginMap.objects['marker_property_' + markerId]; + self.pluginMarkers.remove(markerId); + resolve(); + return; + } + marker.setVisible(true); + self.pluginMarkers[markerId] = STATUS.CREATED; resolve(); - return; - } - marker.setVisible(true); - self.pluginMarkers[markerId] = STATUS.CREATED; - resolve(); - }); + }); }); }; @@ -439,8 +433,8 @@ PluginMarkerCluster.prototype.remove = function(onSuccess, onError, args) { PluginMarkerCluster.prototype.onClusterEvent = function(evtName, marker) { var self = this, mapId = self.pluginMap.id; - var overlayId = marker.get("overlayId"); - var tmp = overlayId.split("-"); + var overlayId = marker.get('overlayId'); + var tmp = overlayId.split('-'); var clusterId = tmp[0]; var markerId = tmp[1]; var latLng = marker.getPosition(); @@ -481,7 +475,7 @@ function ClusterIconClass(options) { //----------------------------------------- // Create a canvas to draw label //----------------------------------------- - var canvas = document.createElement("canvas"); + var canvas = document.createElement('canvas'); canvas.width = 50; canvas.height = 50; canvas.style.visibility = 'hidden'; @@ -524,15 +518,15 @@ function ClusterIconClass(options) { self.addListener('icon_changed', function() { var icon = self.get('icon'); - if (typeof icon === "string") { + if (typeof icon === 'string') { icon = { - "url": icon + 'url': icon }; } var iconUrl = icon.url; - if (typeof icon === "object") { - if (typeof icon.size === "object" && + if (typeof icon === 'object') { + if (typeof icon.size === 'object' && icon.size.width && icon.size.height) { icon.anchor = new google.maps.Point(icon.size.width / 2, icon.size.height / 2); iconMarker.setIcon(icon); @@ -583,8 +577,8 @@ ClusterIconClass.prototype.onRemove = function() { }; ClusterIconClass.prototype.draw = function() { var self = this, - icon = self.get("icon"); - if (typeof icon === "string") { + icon = self.get('icon'); + if (typeof icon === 'string') { icon = { 'url': icon }; @@ -594,12 +588,12 @@ ClusterIconClass.prototype.draw = function() { return; } self.set('prevText', icon.label.text); - self.get("labelMarker").set("opacity", 0); + self.get('labelMarker').set('opacity', 0); - (new Promise(function(resolve, reject) { + (new Promise(function(resolve) { var iconUrl = icon.url; - if (typeof icon === "object") { - if (typeof icon.size === "object" && + if (typeof icon === 'object') { + if (typeof icon.size === 'object' && icon.size.width && icon.size.height) { return resolve(icon.size); } @@ -626,68 +620,68 @@ ClusterIconClass.prototype.draw = function() { }; img.src = iconUrl; })) - .then(function(iconSize) { - var canvas = self.get('canvas'), - ctx = canvas.getContext("2d"); + .then(function(iconSize) { + var canvas = self.get('canvas'), + ctx = canvas.getContext('2d'); canvas.width = iconSize.width; canvas.height = iconSize.height; - var labelOptions = icon.label || { - fontSize: 10, - bold: false, - italic: false - }; - ctx.clearRect(0, 0, canvas.width, canvas.height); - // debug - //ctx.fillStyle="#FF000077"; - //ctx.fillRect(0, 0, canvas.width, canvas.height); - - if (labelOptions.text) { - var fontStyles = []; - - if ('color' in labelOptions) { - ctx.fillStyle = [ - 'rgba(', - labelOptions.color[0], - ",", - labelOptions.color[1], - ",", - labelOptions.color[2], - ",", - labelOptions.color[3] / 255, - ')'].join(""); - } else { - ctx.fillStyle = 'black'; - } + var labelOptions = icon.label || { + fontSize: 10, + bold: false, + italic: false + }; + ctx.clearRect(0, 0, canvas.width, canvas.height); + // debug + //ctx.fillStyle="#FF000077"; + //ctx.fillRect(0, 0, canvas.width, canvas.height); + + if (labelOptions.text) { + var fontStyles = []; + + if ('color' in labelOptions) { + ctx.fillStyle = [ + 'rgba(', + labelOptions.color[0], + ',', + labelOptions.color[1], + ',', + labelOptions.color[2], + ',', + labelOptions.color[3] / 255, + ')'].join(''); + } else { + ctx.fillStyle = 'black'; + } - if (labelOptions.italic === true) { - fontStyles.push("italic"); - } - if (labelOptions.bold === true) { - fontStyles.push("bold"); - } + if (labelOptions.italic === true) { + fontStyles.push('italic'); + } + if (labelOptions.bold === true) { + fontStyles.push('bold'); + } - fontStyles.push(parseInt(labelOptions.fontSize || "10", 10) + "px"); + fontStyles.push(parseInt(labelOptions.fontSize || '10', 10) + 'px'); - fontStyles.push('Arial'); + fontStyles.push('Arial'); - ctx.font = fontStyles.join(' '); - ctx.textBaseline = 'middle'; - ctx.textAlign = 'center'; - ctx.fillText(labelOptions.text, iconSize.width / 2, iconSize.height / 2); - // debug - //ctx.fillText(selfId.split("-")[1], iconSize.width / 2, iconSize.height / 2); + ctx.font = fontStyles.join(' '); + ctx.textBaseline = 'middle'; + ctx.textAlign = 'center'; + ctx.fillText(labelOptions.text, iconSize.width / 2, iconSize.height / 2); + // debug + //ctx.fillText(selfId.split("-")[1], iconSize.width / 2, iconSize.height / 2); - } + } - self.get('labelMarker').set('icon', { - 'url': canvas.toDataURL(), - 'anchor': self.get('labelMarkerAnchor') + self.get('labelMarker').set('icon', { + 'url': canvas.toDataURL(), + 'anchor': self.get('labelMarkerAnchor') + }); + setTimeout(function() { + self.set('opacity', 1); + }, 10); }); - setTimeout(function() { - self.set("opacity", 1); - }, 10); - }); }; @@ -704,7 +698,7 @@ ClusterIconClass.prototype.setPosition = function(position) { self.set('position', position); }; -ClusterIconClass.prototype.getPosition = function(position) { +ClusterIconClass.prototype.getPosition = function() { var self = this; return self.get('position'); }; diff --git a/src/browser/PluginPolygon.js b/src/browser/PluginPolygon.js index 4b51c45fe..91d37816c 100644 --- a/src/browser/PluginPolygon.js +++ b/src/browser/PluginPolygon.js @@ -1,15 +1,11 @@ - - - var utils = require('cordova/utils'), event = require('cordova-plugin-googlemaps.event'), - BaseClass = require('cordova-plugin-googlemaps.BaseClass'), - LatLng = require('cordova-plugin-googlemaps.LatLng'); + BaseClass = require('cordova-plugin-googlemaps.BaseClass'); function PluginPolygon(pluginMap) { var self = this; BaseClass.apply(self); - Object.defineProperty(self, "pluginMap", { + Object.defineProperty(self, 'pluginMap', { value: pluginMap, writable: false }); @@ -219,7 +215,7 @@ PluginPolygon.prototype.removePointAt = function(onSuccess, onError, args) { var polygon = self.pluginMap.objects[overlayId]; if (polygon) { var index = args[1]; - polygon.getPath().removeAt(index, latLng); + polygon.getPath().removeAt(index); } onSuccess(); }; @@ -254,7 +250,6 @@ PluginPolygon.prototype.insertPointOfHoleAt = function(onSuccess, onError, args) polygon = self.pluginMap.objects[overlayId]; if (polygon) { - var index = args[1]; var latLng = new google.maps.LatLng(position.lat, position.lng); var paths = polygon.getPaths(); var hole = null; @@ -279,7 +274,6 @@ PluginPolygon.prototype.setPointOfHoleAt = function(onSuccess, onError, args) { polygon = self.pluginMap.objects[overlayId]; if (polygon) { - var index = args[1]; var latLng = new google.maps.LatLng(position.lat, position.lng); polygon.getPaths().getAt(holeIndex).setAt(pointIndex, latLng); } diff --git a/src/browser/PluginPolyline.js b/src/browser/PluginPolyline.js index 989581c99..65bcc39a0 100644 --- a/src/browser/PluginPolyline.js +++ b/src/browser/PluginPolyline.js @@ -2,13 +2,12 @@ var utils = require('cordova/utils'), event = require('cordova-plugin-googlemaps.event'), - BaseClass = require('cordova-plugin-googlemaps.BaseClass'), - LatLng = require('cordova-plugin-googlemaps.LatLng'); + BaseClass = require('cordova-plugin-googlemaps.BaseClass'); function PluginPolyline(pluginMap) { var self = this; BaseClass.apply(self); - Object.defineProperty(self, "pluginMap", { + Object.defineProperty(self, 'pluginMap', { value: pluginMap, writable: false }); @@ -197,7 +196,7 @@ PluginPolyline.prototype.removePointAt = function(onSuccess, onError, args) { var polyline = self.pluginMap.objects[overlayId]; if (polyline) { var index = args[1]; - polyline.getPath().removeAt(index, latLng); + polyline.getPath().removeAt(index); } onSuccess(); }; diff --git a/src/browser/PluginStreetViewPanorama.js b/src/browser/PluginStreetViewPanorama.js index 1879b8ed0..f47e17c98 100644 --- a/src/browser/PluginStreetViewPanorama.js +++ b/src/browser/PluginStreetViewPanorama.js @@ -2,8 +2,7 @@ var utils = require('cordova/utils'), event = require('cordova-plugin-googlemaps.event'), - BaseClass = require('cordova-plugin-googlemaps.BaseClass'), - LatLng = require('cordova-plugin-googlemaps.LatLng'); + BaseClass = require('cordova-plugin-googlemaps.BaseClass'); function displayGrayMap(container) { var gmErrorContent = document.querySelector('.gm-err-container'); @@ -16,22 +15,22 @@ function displayGrayMap(container) { '

Can not display panorama.
Check the developer console.

', '', '' - ].join("\n"); + ].join('\n'); } } -function PluginStreetViewPanorama(panoramaId, options, panoramaDivId) { +function PluginStreetViewPanorama(panoramaId, options) { var self = this; BaseClass.apply(this); - var panoramaDiv = document.querySelector("[__pluginMapId='" + panoramaId + "']"); + var panoramaDiv = document.querySelector('[__pluginMapId=\'' + panoramaId + '\']'); panoramaDiv.style.backgroundColor = 'rgb(229, 227, 223)'; - var container = document.createElement("div"); - container.style.userSelect="none"; - container.style["-webkit-user-select"]="none"; - container.style["-moz-user-select"]="none"; - container.style["-ms-user-select"]="none"; - panoramaDiv.style.position = "relative"; - container.style.position = "absolute"; + var container = document.createElement('div'); + container.style.userSelect='none'; + container.style['-webkit-user-select']='none'; + container.style['-moz-user-select']='none'; + container.style['-ms-user-select']='none'; + panoramaDiv.style.position = 'relative'; + container.style.position = 'absolute'; container.style.top = 0; container.style.bottom = 0; container.style.right = 0; @@ -39,29 +38,29 @@ function PluginStreetViewPanorama(panoramaId, options, panoramaDivId) { container.style.zIndex = 0; panoramaDiv.insertBefore(container, panoramaDiv.firstElementChild); - self.set("isGoogleReady", false); - self.set("container", container); + self.set('isGoogleReady', false); + self.set('container', container); self.PLUGINS = {}; - Object.defineProperty(self, "id", { + Object.defineProperty(self, 'id', { value: panoramaId, writable: false }); - self.one("googleready", function() { - self.set("isGoogleReady", true); + self.one('googleready', function() { + self.set('isGoogleReady', true); var service = new google.maps.StreetViewService(); self.set('service', service); new Promise(function(resolve, reject) { if (options.camera) { var request = {}; - if (typeof options.camera.target === "string") { + if (typeof options.camera.target === 'string') { request.pano = options.camera.target; } else { request.location = options.camera.target; request.radius = options.camera.radius | 50; - request.source = options.camera.source === "OUTDOOR" ? + request.source = options.camera.source === 'OUTDOOR' ? google.maps.StreetViewSource.OUTDOOR : google.maps.StreetViewSource.DEFAULT; } var timeoutError = setTimeout(function() { @@ -83,61 +82,61 @@ function PluginStreetViewPanorama(panoramaId, options, panoramaDivId) { resolve(); } }) - .then(function(panoId) { - - var stOptions = { - 'addressControl': options.controls.streetNames, - 'showRoadLabels': options.controls.streetNames, - 'linksControl': options.controls.navigation, - 'panControl': options.gestures.panning, - 'zoomControl': options.gestures.zoom, - 'scrollwheel': options.gestures.zoom, - 'pano': panoId - }; - if (options.camera) { - if ('zoom' in options.camera) { - stOptions.zoom = options.camera.zoom; - } - var pov; - if ('tilt' in options.camera) { - pov = {}; - pov.pitch = options.camera.tilt; - } - if ('bearing' in options.camera) { - pov = pov || {}; - pov.heading = options.camera.bearing; - } - if (pov) { - stOptions.pov = pov; - } - } - - google.maps.event.addDomListener(container, 'click', function(evt) { - var pov = panorama.getPov(); - var clickInfo = { - 'orientation': { - 'bearing': pov.heading, - 'tilt': pov.pitch - }, - 'point': [evt.clientX, evt.clientY] + .then(function(panoId) { + + var stOptions = { + 'addressControl': options.controls.streetNames, + 'showRoadLabels': options.controls.streetNames, + 'linksControl': options.controls.navigation, + 'panControl': options.gestures.panning, + 'zoomControl': options.gestures.zoom, + 'scrollwheel': options.gestures.zoom, + 'pano': panoId }; - if (self.id in plugin.google.maps) { - plugin.google.maps[self.id]({ - 'evtName': event.PANORAMA_CLICK, - 'callback': '_onPanoramaEvent', - 'args': [clickInfo] - }); + if (options.camera) { + if ('zoom' in options.camera) { + stOptions.zoom = options.camera.zoom; + } + var pov; + if ('tilt' in options.camera) { + pov = {}; + pov.pitch = options.camera.tilt; + } + if ('bearing' in options.camera) { + pov = pov || {}; + pov.heading = options.camera.bearing; + } + if (pov) { + stOptions.pov = pov; + } } - }); - var panorama = new google.maps.StreetViewPanorama(container, stOptions); - self.set('panorama', panorama); - self.trigger(event.PANORAMA_READY); - panorama.addListener("position_changed", self._onPanoChangedEvent.bind(self, panorama)); - panorama.addListener("pov_changed", self._onCameraEvent.bind(self, panorama)); - panorama.addListener("zoom_changed", self._onCameraEvent.bind(self, panorama)); + google.maps.event.addDomListener(container, 'click', function(evt) { + var pov = panorama.getPov(); + var clickInfo = { + 'orientation': { + 'bearing': pov.heading, + 'tilt': pov.pitch + }, + 'point': [evt.clientX, evt.clientY] + }; + if (self.id in plugin.google.maps) { + plugin.google.maps[self.id]({ + 'evtName': event.PANORAMA_CLICK, + 'callback': '_onPanoramaEvent', + 'args': [clickInfo] + }); + } + }); + var panorama = new google.maps.StreetViewPanorama(container, stOptions); + self.set('panorama', panorama); - }); + self.trigger(event.PANORAMA_READY); + panorama.addListener('position_changed', self._onPanoChangedEvent.bind(self, panorama)); + panorama.addListener('pov_changed', self._onCameraEvent.bind(self, panorama)); + panorama.addListener('zoom_changed', self._onCameraEvent.bind(self, panorama)); + + }); }); @@ -147,7 +146,7 @@ utils.extend(PluginStreetViewPanorama, BaseClass); PluginStreetViewPanorama.prototype.setPanningGesturesEnabled = function(onSuccess, onError, args) { var self = this; - var panorama = self.get("panorama"); + var panorama = self.get('panorama'); var boolValue = args[0] === true; if (panorama) { @@ -161,7 +160,7 @@ PluginStreetViewPanorama.prototype.setPanningGesturesEnabled = function(onSucces PluginStreetViewPanorama.prototype.setZoomGesturesEnabled = function(onSuccess, onError, args) { var self = this; - var panorama = self.get("panorama"); + var panorama = self.get('panorama'); var boolValue = args[0] === true; if (panorama) { @@ -177,7 +176,7 @@ PluginStreetViewPanorama.prototype.setZoomGesturesEnabled = function(onSuccess, PluginStreetViewPanorama.prototype.setNavigationEnabled = function(onSuccess, onError, args) { var self = this; - var panorama = self.get("panorama"); + var panorama = self.get('panorama'); var boolValue = args[0] === true; if (panorama) { @@ -191,7 +190,7 @@ PluginStreetViewPanorama.prototype.setNavigationEnabled = function(onSuccess, on PluginStreetViewPanorama.prototype.setStreetNamesEnabled = function(onSuccess, onError, args) { var self = this; - var panorama = self.get("panorama"); + var panorama = self.get('panorama'); var boolValue = args[0] === true; if (panorama) { @@ -205,7 +204,7 @@ PluginStreetViewPanorama.prototype.setStreetNamesEnabled = function(onSuccess, o }; PluginStreetViewPanorama.prototype.setStreetNamesEnabled = function(onSuccess, onError, args) { var self = this; - var panorama = self.get("panorama"); + var panorama = self.get('panorama'); var boolValue = args[0] === true; if (panorama) { @@ -219,7 +218,7 @@ PluginStreetViewPanorama.prototype.setStreetNamesEnabled = function(onSuccess, o PluginStreetViewPanorama.prototype.setPosition = function(onSuccess, onError, args) { var self = this; - var panorama = self.get("panorama"); + var panorama = self.get('panorama'); var camera = args[0]; if (panorama) { @@ -227,12 +226,12 @@ PluginStreetViewPanorama.prototype.setPosition = function(onSuccess, onError, ar new Promise(function(resolve, reject) { var request = {}; - if (typeof camera.target === "string") { + if (typeof camera.target === 'string') { request.pano = camera.target; } else { request.location = camera.target; request.radius = camera.radius | 50; - request.source = camera.source === "OUTDOOR" ? + request.source = camera.source === 'OUTDOOR' ? google.maps.StreetViewSource.OUTDOOR : google.maps.StreetViewSource.DEFAULT; } var timeoutError = setTimeout(function() { @@ -248,11 +247,11 @@ PluginStreetViewPanorama.prototype.setPosition = function(onSuccess, onError, ar } }); }) - .then(function(panoId) { - panorama.setPano(panoId); - onSuccess(); - }) - .catch(onError); + .then(function(panoId) { + panorama.setPano(panoId); + onSuccess(); + }) + .catch(onError); } else { onError('panorama has been already removed.'); } @@ -261,7 +260,7 @@ PluginStreetViewPanorama.prototype.setPosition = function(onSuccess, onError, ar PluginStreetViewPanorama.prototype.setPov = function(onSuccess, onError, args) { var self = this; - var panorama = self.get("panorama"); + var panorama = self.get('panorama'); var povRequest = args[0]; if (panorama) { diff --git a/src/browser/PluginTileOverlay.js b/src/browser/PluginTileOverlay.js index 3aa460b32..fe173e2ee 100644 --- a/src/browser/PluginTileOverlay.js +++ b/src/browser/PluginTileOverlay.js @@ -1,12 +1,9 @@ var utils = require('cordova/utils'), - event = require('cordova-plugin-googlemaps.event'), - BaseClass = require('cordova-plugin-googlemaps.BaseClass'), - LatLng = require('cordova-plugin-googlemaps.LatLng'); + BaseClass = require('cordova-plugin-googlemaps.BaseClass'); function TileOverlay(mapId, hashCode, options) { - var self = this, - tileSize = 256, + var tileSize = 256, tileCaches = {}, _opacity = 'opacity' in options ? options.opacity : 1; @@ -49,9 +46,9 @@ function TileOverlay(mapId, hashCode, options) { }); }, - getTile: function(coord, zoom, owner) { + getTile: function(coord, zoom) { - var cacheId = [mapId, hashCode, coord.x, coord.y, zoom].join("-"); + var cacheId = [mapId, hashCode, coord.x, coord.y, zoom].join('-'); if (cacheId in tileCaches) { return tileCaches[cacheId]; } else { @@ -62,12 +59,12 @@ function TileOverlay(mapId, hashCode, options) { div.style.visibility = 'hidden'; if (options.debug) { - div.style.borderLeft = "1px solid red"; - div.style.borderTop = "1px solid red"; + div.style.borderLeft = '1px solid red'; + div.style.borderTop = '1px solid red'; div.style.color = 'red'; div.style.fontSize = '12px'; div.style.padding = '1em'; - div.innerHTML = "x = " + coord.x + ", y = " + coord.y + ", zoom = " + zoom; + div.innerHTML = 'x = ' + coord.x + ', y = ' + coord.y + ', zoom = ' + zoom; } div.setAttribute('cacheId', cacheId); @@ -102,7 +99,7 @@ function TileOverlay(mapId, hashCode, options) { function PluginTileOverlay(pluginMap) { var self = this; BaseClass.apply(self); - Object.defineProperty(self, "pluginMap", { + Object.defineProperty(self, 'pluginMap', { value: pluginMap, enumerable: false, writable: false @@ -119,7 +116,7 @@ PluginTileOverlay.prototype._create = function(onSuccess, onError, args) { tileoverlayId = 'tileoverlay_' + hashCode, pluginOptions = args[1], mapId = self.pluginMap.id, - getTileEventName = mapId + "-" + hashCode + "-tileoverlay"; + getTileEventName = mapId + '-' + hashCode + '-tileoverlay'; pluginOptions.getTile = function(x, y, zoom, urlCallbackId) { cordova.fireDocumentEvent(getTileEventName, { @@ -141,7 +138,7 @@ PluginTileOverlay.prototype._create = function(onSuccess, onError, args) { return; } if (layer.zIndex === undefined) { - layer.zIndex = idx; + layer.zIndex = idx; } if (!layer.getZIndex) { layer.getZIndex = function() { @@ -182,7 +179,7 @@ PluginTileOverlay.prototype.onGetTileUrlFromJS = function(onSuccess, onError, ar cacheId = args[1], tileUrl = args[2]; - var tmp = cacheId.split(/\-/), + var tmp = cacheId.split(/-/), hashCode = tmp[1], tileoverlayId = 'tileoverlay_' + hashCode; @@ -190,7 +187,7 @@ PluginTileOverlay.prototype.onGetTileUrlFromJS = function(onSuccess, onError, ar if (tileLayer && tileLayer.getTileFromCache(cacheId)) { var tile = tileLayer.getTileFromCache(cacheId); - tile.style.backgroundImage = "url('" + tileUrl + "')"; + tile.style.backgroundImage = 'url(\'' + tileUrl + '\')'; tile.style.visibility = tileLayer.visible ? 'visible': 'hidden'; if (tileLayer.fadeIn) { @@ -218,7 +215,7 @@ PluginTileOverlay.prototype.setOpacity = function(onSuccess, onError, args) { var opacity = args[1]; var tileoverlay = self.pluginMap.objects[overlayId]; if (tileoverlay) { - tileoverlay.setOpacity(args[1]); + tileoverlay.setOpacity(opacity); } onSuccess(); }; @@ -285,7 +282,7 @@ module.exports = PluginTileOverlay; function fadeInAnimation(el, time, maxOpacity) { el.style.opacity = 0; - var timeFunc = typeof window.requestAnimationFrame === "function" ? requestAnimationFrame : setTimeout; + var timeFunc = typeof window.requestAnimationFrame === 'function' ? requestAnimationFrame : setTimeout; var last = Date.now(); var tick = function() { diff --git a/src/ios/check_sdk_version.js b/src/ios/check_sdk_version.js index 9dadc99b0..a66480038 100644 --- a/src/ios/check_sdk_version.js +++ b/src/ios/check_sdk_version.js @@ -1,12 +1,12 @@ -module.exports = function(ctx) { +module.exports = function (ctx) { var PluginInfoProvider = ctx.requireCordovaModule('cordova-common').PluginInfoProvider; var Q = ctx.requireCordovaModule('q'), - path = ctx.requireCordovaModule('path'); + path = ctx.requireCordovaModule('path'); var projectRoot = ctx.opts.projectRoot; - return Q.Promise(function(resolve, reject, notify) { + return Q.Promise(function (resolve, reject) { var pluginsDir = path.join(projectRoot, 'plugins'); var pluginInfoProvider = new PluginInfoProvider(); @@ -15,26 +15,26 @@ module.exports = function(ctx) { var needToUninstall = false; for (var i = 0; i < plugins.length; i++) { pluginInfo = plugins[i]; - if (pluginInfo.id === "com.googlemaps.ios") { + if (pluginInfo.id === 'com.googlemaps.ios') { needToUninstall = true; break; } } if (needToUninstall) { - console.info("--[cordova-plugin-googlemaps]------------------------"); - console.info("From version 2.4.5, the cordova-plugin-googlemaps uses CocoaPod."); - console.info("No longer necessary com.googlemaps.ios plugin."); - console.info("Automatic uninstalling com.googlemaps.ios plugin..."); - console.info("-----------------------------------------------------"); + console.info('--[cordova-plugin-googlemaps]------------------------'); + console.info('From version 2.4.5, the cordova-plugin-googlemaps uses CocoaPod.'); + console.info('No longer necessary com.googlemaps.ios plugin.'); + console.info('Automatic uninstalling com.googlemaps.ios plugin...'); + console.info('-----------------------------------------------------'); var exec = require('child_process').exec; - exec('cordova plugin rm com.googlemaps.ios 2>&1', function(err, stdout) { + exec('cordova plugin rm com.googlemaps.ios 2>&1', function (err, stdout) { if (err) { reject(err); } else { console.log(stdout); - exec('npm uninstall cordova-plugin-googlemaps-sdk --save 2>&1', function() { + exec('npm uninstall cordova-plugin-googlemaps-sdk --save 2>&1', function () { resolve(); }); } diff --git a/www/BaseArrayClass.js b/www/BaseArrayClass.js index 53e68458c..ff23a8500 100644 --- a/www/BaseArrayClass.js +++ b/www/BaseArrayClass.js @@ -21,7 +21,7 @@ function BaseArrayClass(array) { utils.extend(BaseArrayClass, BaseClass); BaseArrayClass.prototype.mapSeries = function(fn, callback) { - if (typeof fn !== "function" || typeof callback !== "function") { + if (typeof fn !== 'function' || typeof callback !== 'function') { return; } var self = this; @@ -50,7 +50,7 @@ BaseArrayClass.prototype.mapSeries = function(fn, callback) { }; BaseArrayClass.prototype.mapAsync = function(fn, callback) { - if (typeof fn !== "function" || typeof callback !== "function") { + if (typeof fn !== 'function' || typeof callback !== 'function') { return; } var self = this; @@ -91,11 +91,10 @@ BaseArrayClass.prototype.mapAsync = function(fn, callback) { BaseArrayClass.prototype.map = function(fn, callback) { var self = this; - if (typeof fn !== "function") { + if (typeof fn !== 'function') { return; } - var results = []; - if (typeof fn === "function" && typeof callback !== "function") { + if (typeof fn === 'function' && typeof callback !== 'function') { //------------------------ // example: // var values = baseArray.map(function(item, idx) { @@ -109,7 +108,7 @@ BaseArrayClass.prototype.map = function(fn, callback) { }; BaseArrayClass.prototype.forEachAsync = function(fn, callback) { - if (typeof fn !== "function" || typeof callback !== "function") { + if (typeof fn !== 'function' || typeof callback !== 'function') { return; } var self = this; @@ -129,25 +128,23 @@ BaseArrayClass.prototype.forEachAsync = function(fn, callback) { return; } - for (var i = 0; i < self[ARRAY_FIELD].length; i++) { - (function(item, idx) { - fn.call(self, item, function() { - finishCnt++; - if (finishCnt === _arrayLength) { - callback.call(self); - } - }); - })(self[ARRAY_FIELD][i], i); - } + self[ARRAY_FIELD].forEach(function(item) { + fn.call(self, item, function() { + finishCnt++; + if (finishCnt === _arrayLength) { + callback.call(self); + } + }); + }); }; BaseArrayClass.prototype.forEach = function(fn, callback) { var self = this; - if (typeof fn !== "function") { + if (typeof fn !== 'function') { return; } - if (typeof fn === "function" && typeof callback !== "function") { + if (typeof fn === 'function' && typeof callback !== 'function') { //------------------------ // example: // baseArray.forEach(function(item, idx) { @@ -162,7 +159,7 @@ BaseArrayClass.prototype.forEach = function(fn, callback) { BaseArrayClass.prototype.filterAsync = function(fn, callback) { var self = this; - if (typeof fn !== "function" || typeof callback !== "function") { + if (typeof fn !== 'function' || typeof callback !== 'function') { return; } //------------------------ @@ -181,27 +178,25 @@ BaseArrayClass.prototype.filterAsync = function(fn, callback) { return; } var results = []; - for (var i = 0; i < self[ARRAY_FIELD].length; i++) { - (function(item, idx) { - fn.call(self, item, function(isOk) { - if (isOk) { - results.push(item); - } - finishCnt++; - if (finishCnt === _arrayLength) { - callback.call(self, results); - } - }); - })(self[ARRAY_FIELD][i], i); - } + self[ARRAY_FIELD].forEach(function(item) { + fn.call(self, item, function(isOk) { + if (isOk) { + results.push(item); + } + finishCnt++; + if (finishCnt === _arrayLength) { + callback.call(self, results); + } + }); + }); }; BaseArrayClass.prototype.filter = function(fn, callback) { var self = this; - if (typeof fn !== "function") { + if (typeof fn !== 'function') { return; } - if (typeof fn === "function" && typeof callback !== "function") { + if (typeof fn === 'function' && typeof callback !== 'function') { //------------------------ // example: // baseArray.filter(function(item, idx) { @@ -230,7 +225,7 @@ BaseArrayClass.prototype.push = function(value, noNotify) { var self = this; self[ARRAY_FIELD].push(value); if (noNotify !== true) { - self.trigger("insert_at", self[ARRAY_FIELD].length - 1); + self.trigger('insert_at', self[ARRAY_FIELD].length - 1); } return self[ARRAY_FIELD].length; }; @@ -244,7 +239,7 @@ BaseArrayClass.prototype.insertAt = function(index, value, noNotify) { } self[ARRAY_FIELD][index] = value; if (noNotify !== true) { - self.trigger("insert_at", index); + self.trigger('insert_at', index); } }; @@ -262,7 +257,7 @@ BaseArrayClass.prototype.setAt = function(index, value, noNotify) { var prev = self[ARRAY_FIELD][index]; self[ARRAY_FIELD][index] = value; if (noNotify !== true) { - self.trigger("set_at", index, prev); + self.trigger('set_at', index, prev); } }; @@ -271,7 +266,7 @@ BaseArrayClass.prototype.removeAt = function(index, noNotify) { var value = self[ARRAY_FIELD][index]; self[ARRAY_FIELD].splice(index, 1); if (noNotify !== true) { - self.trigger("remove_at", index, value); + self.trigger('remove_at', index, value); } return value; }; @@ -281,7 +276,7 @@ BaseArrayClass.prototype.pop = function(noNotify) { var index = self[ARRAY_FIELD].length - 1; var value = self[ARRAY_FIELD].pop(); if (noNotify !== true) { - self.trigger("remove_at", index, value); + self.trigger('remove_at', index, value); } return value; }; diff --git a/www/BaseClass.js b/www/BaseClass.js index f3edc5e7e..d30eeb150 100644 --- a/www/BaseClass.js +++ b/www/BaseClass.js @@ -1,4 +1,3 @@ - var VARS_FIELD = typeof Symbol === 'undefined' ? '__vars' + Date.now() : Symbol('vars'); var SUBSCRIPTIONS_FIELD = typeof Symbol === 'undefined' ? '__subs' + Date.now() : Symbol('subscriptions'); @@ -65,25 +64,25 @@ BaseClass.prototype = { var args = Array.prototype.slice.call(arguments, 1); var self = this; - keys.forEach(function(_hashCode) { + keys.forEach(function (_hashCode) { if (self[SUBSCRIPTIONS_FIELD] && - self[SUBSCRIPTIONS_FIELD][eventName] && - _hashCode in self[SUBSCRIPTIONS_FIELD][eventName]) { + self[SUBSCRIPTIONS_FIELD][eventName] && + _hashCode in self[SUBSCRIPTIONS_FIELD][eventName]) { var info = self[SUBSCRIPTIONS_FIELD][eventName][_hashCode]; switch (info.kind) { - case 'on': - info.listener.apply(self, args); - break; - case 'onThrottled': - info.args = args; - if (!info.timer) { - info.timer = setTimeout(function() { - info.listener.apply(this, info.args); - info.timer = null; - }.bind(self), info.interval); - } - break; + case 'on': + info.listener.apply(self, args); + break; + case 'onThrottled': + info.args = args; + if (!info.timer) { + info.timer = setTimeout(function () { + info.listener.apply(this, info.args); + info.timer = null; + }.bind(self), info.interval); + } + break; } } }); @@ -92,7 +91,7 @@ BaseClass.prototype = { }, on: function (eventName, listener) { - if (!listener || typeof listener !== "function") { + if (!listener || typeof listener !== 'function') { throw Error('Listener for on()/addEventListener() method is not a function'); } if (!listener._hashCode) { @@ -111,10 +110,10 @@ BaseClass.prototype = { }, onThrottled: function (eventName, listener, interval) { - if (!listener || typeof listener !== "function") { + if (!listener || typeof listener !== 'function') { throw Error('Listener for on()/addEventListener() method is not a function'); } - if (typeof interval !== "number" || interval < 1) { + if (typeof interval !== 'number' || interval < 1) { throw Error('interval argument must be bigger number than 0'); } if (!listener._hashCode) { @@ -125,7 +124,7 @@ BaseClass.prototype = { }); } this[SUBSCRIPTIONS_FIELD][eventName] = this[SUBSCRIPTIONS_FIELD][eventName] || {}; - this[SUBSCRIPTIONS_FIELD][eventName][listener._hashCode] ={ + this[SUBSCRIPTIONS_FIELD][eventName][listener._hashCode] = { 'kind': 'onThrottled', 'interval': interval, 'timer': null, @@ -150,7 +149,7 @@ BaseClass.prototype = { }, one: function (eventName, listener) { - if (!listener || typeof listener !== "function") { + if (!listener || typeof listener !== 'function') { throw Error('Listener for one()/addEventListenerOnce() method is not a function'); } @@ -166,7 +165,7 @@ BaseClass.prototype = { return this; }, - hasEventListener : function (eventName) { + hasEventListener: function (eventName) { return eventName in this[SUBSCRIPTIONS_FIELD]; }, @@ -177,7 +176,7 @@ BaseClass.prototype = { errorHandler: function (error) { if (error) { - if (typeof console.error === "function") { + if (typeof console.error === 'function') { if (this.id) { console.error(this.id, error); } else { diff --git a/www/CameraPosition.js b/www/CameraPosition.js index f12e9bfc1..251707c56 100644 --- a/www/CameraPosition.js +++ b/www/CameraPosition.js @@ -8,13 +8,13 @@ * @property {Number} [duration] The duration of animation *******************************************************************************/ var CameraPosition = function(params) { - var self = this; - self.zoom = params.zoom; - self.tilt = params.tilt; - self.target = params.target; - self.bearing = params.bearing; - self.hashCode = params.hashCode; - self.duration = params.duration; + var self = this; + self.zoom = params.zoom; + self.tilt = params.tilt; + self.target = params.target; + self.bearing = params.bearing; + self.hashCode = params.hashCode; + self.duration = params.duration; }; module.exports = CameraPosition; diff --git a/www/Circle.js b/www/Circle.js index 9aa284b54..de00603e8 100644 --- a/www/Circle.js +++ b/www/Circle.js @@ -1,5 +1,4 @@ -var argscheck = require('cordova/argscheck'), - utils = require('cordova/utils'), +var utils = require('cordova/utils'), common = require('./Common'), LatLngBounds = require('./LatLngBounds'), Overlay = require('./Overlay'); @@ -15,38 +14,38 @@ var Circle = function (map, circleOptions, _exec) { //----------------------------------------------- // Sets event listeners //----------------------------------------------- - self.on("center_changed", function () { - var center = self.get("center"); + self.on('center_changed', function () { + var center = self.get('center'); center.lat = parseFloat(center.lat, 10); center.lng = parseFloat(center.lng, 10); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setCenter', [self.getId(), center.lat, center.lng]); }); - self.on("fillColor_changed", function () { - var color = self.get("fillColor"); + self.on('fillColor_changed', function () { + var color = self.get('fillColor'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setFillColor', [self.getId(), common.HTMLColor2RGBA(color, 0.75)]); }); - self.on("strokeColor_changed", function () { - var color = self.get("strokeColor"); + self.on('strokeColor_changed', function () { + var color = self.get('strokeColor'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setStrokeColor', [self.getId(), common.HTMLColor2RGBA(color, 0.75)]); }); - self.on("strokeWidth_changed", function () { - var width = self.get("strokeWidth"); + self.on('strokeWidth_changed', function () { + var width = self.get('strokeWidth'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setStrokeWidth', [self.getId(), width]); }); - self.on("clickable_changed", function () { - var clickable = self.get("clickable"); + self.on('clickable_changed', function () { + var clickable = self.get('clickable'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setClickable', [self.getId(), clickable]); }); - self.on("radius_changed", function () { - var radius = self.get("radius"); + self.on('radius_changed', function () { + var radius = self.get('radius'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setRadius', [self.getId(), radius]); }); - self.on("zIndex_changed", function () { - var zIndex = self.get("zIndex"); + self.on('zIndex_changed', function () { + var zIndex = self.get('zIndex'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setZIndex', [self.getId(), zIndex]); }); - self.on("visible_changed", function () { - var visible = self.get("visible"); + self.on('visible_changed', function () { + var visible = self.get('visible'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setVisible', [self.getId(), visible]); }); @@ -115,18 +114,17 @@ Circle.prototype.setRadius = function (radius) { Circle.prototype.remove = function (callback) { var self = this; if (self._isRemoved) { - if (typeof callback === "function") { + if (typeof callback === 'function') { return; } else { return Promise.resolve(); } - return; } - Object.defineProperty(self, "_isRemoved", { + Object.defineProperty(self, '_isRemoved', { value: true, writable: false }); - self.trigger(self.id + "_remove"); + self.trigger(self.id + '_remove'); var resolver = function(resolve, reject) { self.exec.call(self, @@ -140,7 +138,7 @@ Circle.prototype.remove = function (callback) { }); }; - if (typeof callback === "function") { + if (typeof callback === 'function') { resolver(callback, self.errorHandler); } else { return new Promise(resolver); @@ -152,8 +150,8 @@ Circle.prototype.getBounds = function () { var d2r = Math.PI / 180; // degrees to radians var r2d = 180 / Math.PI; // radians to degrees var earthsradius = 3963.189; // 3963 is the radius of the earth in miles - var radius = this.get("radius"); - var center = this.get("center"); + var radius = this.get('radius'); + var center = this.get('center'); radius *= 0.000621371192; // find the raidus in lat/lon diff --git a/www/Cluster.js b/www/Cluster.js index f87d0ab92..84ce4f9c2 100644 --- a/www/Cluster.js +++ b/www/Cluster.js @@ -1,10 +1,4 @@ -var argscheck = require('cordova/argscheck'), - utils = require('cordova/utils'), - common = require('./Common'), - Marker = require('./Marker'), - geomodel = require('./geomodel'), - BaseClass = require('./BaseClass'), - LatLngBounds = require('./LatLngBounds'); +var LatLngBounds = require('./LatLngBounds'); /***************************************************************************** * Cluster Class @@ -13,33 +7,33 @@ var Cluster = function(id, geocell) { var obj = {}; var self = this; - Object.defineProperty(self, "id", { + Object.defineProperty(self, 'id', { value: id, writable: false }); - Object.defineProperty(self, "geocell", { + Object.defineProperty(self, 'geocell', { value: geocell, writable: false }); - Object.defineProperty(self, "type", { - value: "Cluster", + Object.defineProperty(self, 'type', { + value: 'Cluster', writable: false }); - Object.defineProperty(self, "_markerOptsArray", { + Object.defineProperty(self, '_markerOptsArray', { value: [], writable: false }); - Object.defineProperty(self, "set", { + Object.defineProperty(self, 'set', { value: function(key, value) { obj[key] = value; }, writable: false }); - Object.defineProperty(self, "get", { + Object.defineProperty(self, 'get', { value: function(key) { return obj[key]; }, @@ -51,17 +45,17 @@ Cluster.prototype.NO_CLUSTER_MODE = 1; Cluster.prototype.CLUSTER_MODE = 2; Cluster.prototype.getPluginName = function() { - return this.map.getId() + "-cluster"; + return this.map.getId() + '-cluster'; }; Cluster.prototype.getBounds = function() { - return this.get("bounds"); + return this.get('bounds'); }; /* Cluster.prototype.getBounds = function() { - var bounds = this.get("bounds"); + var bounds = this.get('bounds'); if (!bounds) { bounds = geomodel.computeBox(this.geocell); - this.set("bounds", bounds); + this.set('bounds', bounds); } return bounds; }; @@ -76,7 +70,7 @@ Cluster.prototype.getMarkers = function() { Cluster.prototype.addMarkers = function(markerRefs) { var self = this; - var bounds = this.get("bounds") || new LatLngBounds(markerRefs[0].position, markerRefs[0].position); + var bounds = this.get('bounds') || new LatLngBounds(markerRefs[0].position, markerRefs[0].position); markerRefs.forEach(function(markerOpts) { if (self._markerOptsArray.indexOf(markerOpts) === -1) { @@ -86,16 +80,16 @@ Cluster.prototype.addMarkers = function(markerRefs) { } }); - this.set("bounds", bounds); + this.set('bounds', bounds); }; Cluster.prototype.getId = function() { return this.id; }; Cluster.prototype.setMode = function(mode) { - this.set("mode", mode); + this.set('mode', mode); }; Cluster.prototype.getMode = function() { - return this.get("mode"); + return this.get('mode'); }; Cluster.prototype.removeMarker = function(markerOpts) { @@ -106,7 +100,7 @@ Cluster.prototype.removeMarker = function(markerOpts) { }; Cluster.prototype.remove = function() { - this.set("isRemoved", true); + this.set('isRemoved', true); this._markerOptsArray.forEach(function(markerOpts) { markerOpts._cluster.isAdded = false; }); diff --git a/www/Common.js b/www/Common.js index acbb6ac4a..65b442d61 100644 --- a/www/Common.js +++ b/www/Common.js @@ -1,231 +1,228 @@ var BaseArrayClass = require('./BaseArrayClass'); -var utils = require("cordova/utils"); +var utils = require('cordova/utils'); var resolvedPromise = typeof Promise == 'undefined' ? null : Promise.resolve(); -var nextTick = resolvedPromise ? function(fn) { resolvedPromise.then(fn); } : function(fn) { setTimeout(fn); }; +var nextTick = resolvedPromise ? function (fn) { + resolvedPromise.then(fn); +} : function (fn) { + setTimeout(fn); +}; //--------------------------- // Convert HTML color to RGB //--------------------------- function isHTMLColorString(inputValue) { - if (!inputValue || typeof inputValue !== "string") { - return false; - } - if (inputValue.match(/^#[0-9A-F]{3}$/i) || - inputValue.match(/^#[0-9A-F]{4}$/i) || - inputValue.match(/^#[0-9A-F]{6}$/i) || - inputValue.match(/^#[0-9A-F]{8}$/i) || - inputValue.match(/^rgba?\([\d,.\s]+\)$/) || - inputValue.match(/^hsla?\([\d%,.\s]+\)$/)) { - return true; - } + if (!inputValue || typeof inputValue !== 'string') { + return false; + } + if (inputValue.match(/^#[0-9A-F]{3}$/i) || + inputValue.match(/^#[0-9A-F]{4}$/i) || + inputValue.match(/^#[0-9A-F]{6}$/i) || + inputValue.match(/^#[0-9A-F]{8}$/i) || + inputValue.match(/^rgba?\([\d,.\s]+\)$/) || + inputValue.match(/^hsla?\([\d%,.\s]+\)$/)) { + return true; + } - inputValue = inputValue.toLowerCase(); - return inputValue in HTML_COLORS; + inputValue = inputValue.toLowerCase(); + return inputValue in HTML_COLORS; } function HTMLColor2RGBA(colorValue, defaultOpacity) { - defaultOpacity = !defaultOpacity ? 1.0 : defaultOpacity; - if (colorValue instanceof Array) { - return colorValue; - } - if (colorValue === "transparent" || !colorValue) { - return [0, 0, 0, 0]; - } - var alpha = Math.floor(255 * defaultOpacity), - matches, - result = { - r: 0, - g: 0, - b: 0 - }; - var colorStr = colorValue.toLowerCase(); - if (colorStr in HTML_COLORS) { - colorStr = HTML_COLORS[colorStr]; - } - if (colorStr.match(/^#([0-9A-F]){3}$/i)) { - matches = colorStr.match(/([0-9A-F])/ig); - - return [ - parseInt(matches[0], 16), - parseInt(matches[1], 16), - parseInt(matches[2], 16), - alpha - ]; - } - - if (colorStr.match(/^#[0-9A-F]{4}$/i)) { - alpha = colorStr.substr(4, 1); - alpha = parseInt(alpha + alpha, 16); - - matches = colorStr.match(/([0-9A-F])/ig); - return [ - parseInt(matches[0], 16), - parseInt(matches[1], 16), - parseInt(matches[2], 16), - alpha - ]; - } + defaultOpacity = !defaultOpacity ? 1.0 : defaultOpacity; + if (colorValue instanceof Array) { + return colorValue; + } + if (colorValue === 'transparent' || !colorValue) { + return [0, 0, 0, 0]; + } + var alpha = Math.floor(255 * defaultOpacity), + matches; + var colorStr = colorValue.toLowerCase(); + if (colorStr in HTML_COLORS) { + colorStr = HTML_COLORS[colorStr]; + } + if (colorStr.match(/^#([0-9A-F]){3}$/i)) { + matches = colorStr.match(/([0-9A-F])/ig); + + return [ + parseInt(matches[0], 16), + parseInt(matches[1], 16), + parseInt(matches[2], 16), + alpha + ]; + } - if (colorStr.match(/^#[0-9A-F]{6}$/i)) { - matches = colorStr.match(/([0-9A-F]{2})/ig); - return [ - parseInt(matches[0], 16), - parseInt(matches[1], 16), - parseInt(matches[2], 16), - alpha - ]; - } - if (colorStr.match(/^#[0-9A-F]{8}$/i)) { - matches = colorStr.match(/([0-9A-F]{2})/ig); - - return [ - parseInt(matches[0], 16), - parseInt(matches[1], 16), - parseInt(matches[2], 16), - parseInt(matches[3], 16) - ]; - } - // convert rgb(), rgba() - if (colorStr.match(/^rgba?\([\d,.\s]+\)$/)) { - matches = colorStr.match(/([\d.]+)/g); - alpha = matches.length == 4 ? Math.floor(parseFloat(matches[3]) * 256) : alpha; - return [ - parseInt(matches[0], 10), - parseInt(matches[1], 10), - parseInt(matches[2], 10), - alpha - ]; - } + if (colorStr.match(/^#[0-9A-F]{4}$/i)) { + alpha = colorStr.substr(4, 1); + alpha = parseInt(alpha + alpha, 16); + + matches = colorStr.match(/([0-9A-F])/ig); + return [ + parseInt(matches[0], 16), + parseInt(matches[1], 16), + parseInt(matches[2], 16), + alpha + ]; + } + if (colorStr.match(/^#[0-9A-F]{6}$/i)) { + matches = colorStr.match(/([0-9A-F]{2})/ig); + return [ + parseInt(matches[0], 16), + parseInt(matches[1], 16), + parseInt(matches[2], 16), + alpha + ]; + } + if (colorStr.match(/^#[0-9A-F]{8}$/i)) { + matches = colorStr.match(/([0-9A-F]{2})/ig); + + return [ + parseInt(matches[0], 16), + parseInt(matches[1], 16), + parseInt(matches[2], 16), + parseInt(matches[3], 16) + ]; + } + // convert rgb(), rgba() + if (colorStr.match(/^rgba?\([\d,.\s]+\)$/)) { + matches = colorStr.match(/([\d.]+)/g); + alpha = matches.length == 4 ? Math.floor(parseFloat(matches[3]) * 256) : alpha; + return [ + parseInt(matches[0], 10), + parseInt(matches[1], 10), + parseInt(matches[2], 10), + alpha + ]; + } - // convert hsl(), hsla() - if (colorStr.match(/^hsla?\([\d%,.\s]+\)$/)) { - matches = colorStr.match(/([\d%.]+)/g); - alpha = matches.length == 4 ? Math.floor(parseFloat(matches[3]) * 256) : alpha; - var rgb = HLStoRGB(matches[0], matches[1], matches[2]); - rgb.push(alpha); - return rgb; - } + // convert hsl(), hsla() + if (colorStr.match(/^hsla?\([\d%,.\s]+\)$/)) { + matches = colorStr.match(/([\d%.]+)/g); + alpha = matches.length == 4 ? Math.floor(parseFloat(matches[3]) * 256) : alpha; + var rgb = HLStoRGB(matches[0], matches[1], matches[2]); + rgb.push(alpha); + return rgb; + } - console.log("Warning: '" + colorValue + "' is not available. The overlay is drew by black."); - return [0, 0, 0, alpha]; + console.warn('Warning: "' + colorValue + '" is not available. The overlay is drew by black.'); + return [0, 0, 0, alpha]; } /** * http://d.hatena.ne.jp/ja9/20100907/1283840213 */ function HLStoRGB(h, l, s) { - var r, g, b; // 0..255 + var r, g, b; // 0..255 - while (h < 0) { - h += 360; - } - h = h % 360; + while (h < 0) { + h += 360; + } + h = h % 360; - // In case of saturation = 0 - if (s === 0) { - // RGB are the same as V - l = Math.round(l * 255); - return [l, l, l]; - } + // In case of saturation = 0 + if (s === 0) { + // RGB are the same as V + l = Math.round(l * 255); + return [l, l, l]; + } - var m2 = (l < 0.5) ? l * (1 + s) : l + s - l * s, - m1 = l * 2 - m2, - tmp; + var m2 = (l < 0.5) ? l * (1 + s) : l + s - l * s, + m1 = l * 2 - m2, + tmp; - tmp = h + 120; - if (tmp > 360) { - tmp = tmp - 360; - } + tmp = h + 120; + if (tmp > 360) { + tmp = tmp - 360; + } - if (tmp < 60) { - r = (m1 + (m2 - m1) * tmp / 60); - } else if (tmp < 180) { - r = m2; - } else if (tmp < 240) { - r = m1 + (m2 - m1) * (240 - tmp) / 60; - } else { - r = m1; - } + if (tmp < 60) { + r = (m1 + (m2 - m1) * tmp / 60); + } else if (tmp < 180) { + r = m2; + } else if (tmp < 240) { + r = m1 + (m2 - m1) * (240 - tmp) / 60; + } else { + r = m1; + } - tmp = h; - if (tmp < 60) { - g = m1 + (m2 - m1) * tmp / 60; - } else if (tmp < 180) { - g = m2; - } else if (tmp < 240) { - g = m1 + (m2 - m1) * (240 - tmp) / 60; - } else { - g = m1; - } + tmp = h; + if (tmp < 60) { + g = m1 + (m2 - m1) * tmp / 60; + } else if (tmp < 180) { + g = m2; + } else if (tmp < 240) { + g = m1 + (m2 - m1) * (240 - tmp) / 60; + } else { + g = m1; + } - tmp = h - 120; - if (tmp < 0) { - tmp = tmp + 360; - } - if (tmp < 60) { - b = m1 + (m2 - m1) * tmp / 60; - } else if (tmp < 180) { - b = m2; - } else if (tmp < 240) { - b = m1 + (m2 - m1) * (240 - tmp) / 60; - } else { - b = m1; - } - return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)]; + tmp = h - 120; + if (tmp < 0) { + tmp = tmp + 360; + } + if (tmp < 60) { + b = m1 + (m2 - m1) * tmp / 60; + } else if (tmp < 180) { + b = m2; + } else if (tmp < 240) { + b = m1 + (m2 - m1) * (240 - tmp) / 60; + } else { + b = m1; + } + return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)]; } function parseBoolean(boolValue) { - return typeof(boolValue) === "string" && boolValue.toLowerCase() === "true" || - boolValue === true || - boolValue === 1; + return typeof (boolValue) === 'string' && boolValue.toLowerCase() === 'true' || + boolValue === true || + boolValue === 1; } function isDom(element) { - return element && - element.nodeType === Node.ELEMENT_NODE && - element instanceof SVGElement === false && - typeof element.getBoundingClientRect === "function"; + return element && + element.nodeType === Node.ELEMENT_NODE && + element instanceof SVGElement === false && + typeof element.getBoundingClientRect === 'function'; } function getDivRect(div) { - if (!div) { - return; - } - var rect; - if (div === document.body) { - rect = div.getBoundingClientRect(); - rect.left = Math.max(rect.left, window.pageOffsetX); - rect.top = Math.max(rect.top, window.pageOffsetY); - rect.width = Math.max(rect.width, window.innerWidth); - rect.height = Math.max(rect.height, window.innerHeight); + if (!div) { + return; + } + var rect; + if (div === document.body) { + rect = div.getBoundingClientRect(); + rect.left = Math.max(rect.left, window.pageOffsetX); + rect.top = Math.max(rect.top, window.pageOffsetY); + rect.width = Math.max(rect.width, window.innerWidth); + rect.height = Math.max(rect.height, window.innerHeight); + rect.right = rect.left + rect.width; + rect.bottom = rect.top + rect.height; + } else { + rect = div.getBoundingClientRect(); + if ('right' in rect === false) { rect.right = rect.left + rect.width; + } + if ('bottom' in rect === false) { rect.bottom = rect.top + rect.height; - } else { - rect = div.getBoundingClientRect(); - if ("right" in rect === false) { - rect.right = rect.left + rect.width; - } - if ("bottom" in rect === false) { - rect.bottom = rect.top + rect.height; - } } - return { - left: rect.left, - top: rect.top, - width: rect.width, - height: rect.height, - right: rect.right, - bottom: rect.bottom - }; + } + return { + left: rect.left, + top: rect.top, + width: rect.width, + height: rect.height, + right: rect.right, + bottom: rect.bottom + }; } var ignoreTags = [ - "pre", "textarea", "p", "form", "input", "caption", "canvas", "svg" + 'pre', 'textarea', 'p', 'form', 'input', 'caption', 'canvas', 'svg' ]; - function shouldWatchByNative(node) { if (!node || node.nodeType !== Node.ELEMENT_NODE || !node.parentNode || node instanceof SVGElement) { if (node === document.body) { @@ -239,8 +236,8 @@ function shouldWatchByNative(node) { return false; } - var classNames = (node.className || "").split(" "); - if (classNames.indexOf("_gmaps_cdv_") > -1) { + var classNames = (node.className || '').split(' '); + if (classNames.indexOf('_gmaps_cdv_') > -1) { return true; } @@ -255,7 +252,7 @@ function shouldWatchByNative(node) { // because the app might start changing the opacity later. //----------------------------------------- //var opacityCSS = getStyle(node, 'opacity'); - //opacityCSS = /^[\d.]+$/.test(opacityCSS + "") ? opacityCSS : 1; + //opacityCSS = /^[\d.]+$/.test(opacityCSS + '') ? opacityCSS : 1; //----------------------------------------- // no longer check the clickable size, @@ -264,302 +261,309 @@ function shouldWatchByNative(node) { // var clickableSize = ( // node.offsetHeight > 0 && node.offsetWidth > 0 || // node.clientHeight > 0 && node.clientWidth > 0); - return displayCSS !== "none" && - visibilityCSS !== "hidden"; + return displayCSS !== 'none' && + visibilityCSS !== 'hidden'; } - // Get z-index order // http://stackoverflow.com/a/24136505 var internalCache = {}; + function _clearInternalCache() { internalCache = undefined; internalCache = {}; } + function _removeCacheById(elemId) { delete internalCache[elemId]; } -function getZIndex(dom) { - if (dom === document.body) { - internalCache = undefined; - internalCache = {}; - } - if (!dom) { - return 0; - } - var z = 0; - if (window.getComputedStyle) { - z = document.defaultView.getComputedStyle(dom, null).getPropertyValue('z-index'); - } - if (dom.currentStyle) { - z = dom.currentStyle['z-index']; - } - var elemId = dom.getAttribute("__pluginDomId"); - var parentNode = dom.parentNode; - var parentZIndex = 0; - if (parentNode && parentNode.nodeType === Node.ELEMENT_NODE) { - var parentElemId = parentNode.getAttribute("__pluginDomId"); - if (parentElemId in internalCache) { - parentZIndex = internalCache[parentElemId]; - } else { - parentZIndex = getZIndex(dom.parentNode); - internalCache[parentElemId] = parentZIndex; - } - } +function getZIndex(dom) { + if (dom === document.body) { + internalCache = undefined; + internalCache = {}; + } + if (!dom) { + return 0; + } - var isInherit = false; - if (z === "unset" || z === "initial") { - z = 0; - } else if (z === "auto" || z === "inherit") { - z = 0; - isInherit = true; + var z = 0; + if (window.getComputedStyle) { + z = document.defaultView.getComputedStyle(dom, null).getPropertyValue('z-index'); + } + if (dom.currentStyle) { + z = dom.currentStyle['z-index']; + } + var elemId = dom.getAttribute('__pluginDomId'); + var parentNode = dom.parentNode; + var parentZIndex = 0; + if (parentNode && parentNode.nodeType === Node.ELEMENT_NODE) { + var parentElemId = parentNode.getAttribute('__pluginDomId'); + if (parentElemId in internalCache) { + parentZIndex = internalCache[parentElemId]; } else { - z = parseInt(z); + parentZIndex = getZIndex(dom.parentNode); + internalCache[parentElemId] = parentZIndex; } - //dom.setAttribute("__ZIndex", z); - internalCache[elemId] = z + parentZIndex; - return { - isInherit: isInherit, - z: z - }; + } + + var isInherit = false; + if (z === 'unset' || z === 'initial') { + z = 0; + } else if (z === 'auto' || z === 'inherit') { + z = 0; + isInherit = true; + } else { + z = parseInt(z); + } + //dom.setAttribute('__ZIndex', z); + internalCache[elemId] = z + parentZIndex; + return { + isInherit: isInherit, + z: z + }; } // Get CSS value of an element // http://stackoverflow.com/a/1388022 -function getStyle(element, styleProperty) -{ - if (window.getComputedStyle) { - return document.defaultView.getComputedStyle(element,null).getPropertyValue(styleProperty); - } else if (element.currentStyle) { - return element.currentStyle[styleProperty]; - } - return; -} - -function getDomInfo(dom, idx) { - return { - size: getDivRect(dom), - depth: getDomDepth(dom, idx) - }; +function getStyle(element, styleProperty) { + if (window.getComputedStyle) { + return document.defaultView.getComputedStyle(element, null).getPropertyValue(styleProperty); + } else if (element.currentStyle) { + return element.currentStyle[styleProperty]; + } + return; } var HTML_COLORS = { - "aliceblue": "#f0f8ff", - "antiquewhite": "#faebd7", - "aqua": "#00ffff", - "aquamarine": "#7fffd4", - "azure": "#f0ffff", - "beige": "#f5f5dc", - "bisque": "#ffe4c4", - "black": "#000000", - "blanchedalmond": "#ffebcd", - "blue": "#0000ff", - "blueviolet": "#8a2be2", - "brown": "#a52a2a", - "burlywood": "#deb887", - "cadetblue": "#5f9ea0", - "chartreuse": "#7fff00", - "chocolate": "#d2691e", - "coral": "#ff7f50", - "cornflowerblue": "#6495ed", - "cornsilk": "#fff8dc", - "crimson": "#dc143c", - "cyan": "#00ffff", - "darkblue": "#00008b", - "darkcyan": "#008b8b", - "darkgoldenrod": "#b8860b", - "darkgray": "#a9a9a9", - "darkgrey": "#a9a9a9", - "darkgreen": "#006400", - "darkkhaki": "#bdb76b", - "darkmagenta": "#8b008b", - "darkolivegreen": "#556b2f", - "darkorange": "#ff8c00", - "darkorchid": "#9932cc", - "darkred": "#8b0000", - "darksalmon": "#e9967a", - "darkseagreen": "#8fbc8f", - "darkslateblue": "#483d8b", - "darkslategray": "#2f4f4f", - "darkslategrey": "#2f4f4f", - "darkturquoise": "#00ced1", - "darkviolet": "#9400d3", - "deeppink": "#ff1493", - "deepskyblue": "#00bfff", - "dimgray": "#696969", - "dimgrey": "#696969", - "dodgerblue": "#1e90ff", - "firebrick": "#b22222", - "floralwhite": "#fffaf0", - "forestgreen": "#228b22", - "fuchsia": "#ff00ff", - "gainsboro": "#dcdcdc", - "ghostwhite": "#f8f8ff", - "gold": "#ffd700", - "goldenrod": "#daa520", - "gray": "#808080", - "grey": "#808080", - "green": "#008000", - "greenyellow": "#adff2f", - "honeydew": "#f0fff0", - "hotpink": "#ff69b4", - "indianred ": "#cd5c5c", - "indigo ": "#4b0082", - "ivory": "#fffff0", - "khaki": "#f0e68c", - "lavender": "#e6e6fa", - "lavenderblush": "#fff0f5", - "lawngreen": "#7cfc00", - "lemonchiffon": "#fffacd", - "lightblue": "#add8e6", - "lightcoral": "#f08080", - "lightcyan": "#e0ffff", - "lightgoldenrodyellow": "#fafad2", - "lightgray": "#d3d3d3", - "lightgrey": "#d3d3d3", - "lightgreen": "#90ee90", - "lightpink": "#ffb6c1", - "lightsalmon": "#ffa07a", - "lightseagreen": "#20b2aa", - "lightskyblue": "#87cefa", - "lightslategray": "#778899", - "lightslategrey": "#778899", - "lightsteelblue": "#b0c4de", - "lightyellow": "#ffffe0", - "lime": "#00ff00", - "limegreen": "#32cd32", - "linen": "#faf0e6", - "magenta": "#ff00ff", - "maroon": "#800000", - "mediumaquamarine": "#66cdaa", - "mediumblue": "#0000cd", - "mediumorchid": "#ba55d3", - "mediumpurple": "#9370db", - "mediumseagreen": "#3cb371", - "mediumslateblue": "#7b68ee", - "mediumspringgreen": "#00fa9a", - "mediumturquoise": "#48d1cc", - "mediumvioletred": "#c71585", - "midnightblue": "#191970", - "mintcream": "#f5fffa", - "mistyrose": "#ffe4e1", - "moccasin": "#ffe4b5", - "navajowhite": "#ffdead", - "navy": "#000080", - "oldlace": "#fdf5e6", - "olive": "#808000", - "olivedrab": "#6b8e23", - "orange": "#ffa500", - "orangered": "#ff4500", - "orchid": "#da70d6", - "palegoldenrod": "#eee8aa", - "palegreen": "#98fb98", - "paleturquoise": "#afeeee", - "palevioletred": "#db7093", - "papayawhip": "#ffefd5", - "peachpuff": "#ffdab9", - "peru": "#cd853f", - "pink": "#ffc0cb", - "plum": "#dda0dd", - "powderblue": "#b0e0e6", - "purple": "#800080", - "rebeccapurple": "#663399", - "red": "#ff0000", - "rosybrown": "#bc8f8f", - "royalblue": "#4169e1", - "saddlebrown": "#8b4513", - "salmon": "#fa8072", - "sandybrown": "#f4a460", - "seagreen": "#2e8b57", - "seashell": "#fff5ee", - "sienna": "#a0522d", - "silver": "#c0c0c0", - "skyblue": "#87ceeb", - "slateblue": "#6a5acd", - "slategray": "#708090", - "slategrey": "#708090", - "snow": "#fffafa", - "springgreen": "#00ff7f", - "steelblue": "#4682b4", - "tan": "#d2b48c", - "teal": "#008080", - "thistle": "#d8bfd8", - "tomato": "#ff6347", - "turquoise": "#40e0d0", - "violet": "#ee82ee", - "wheat": "#f5deb3", - "white": "#ffffff", - "whitesmoke": "#f5f5f5", - "yellow": "#ffff00", - "yellowgreen": "#9acd32" + 'aliceblue': '#f0f8ff', + 'antiquewhite': '#faebd7', + 'aqua': '#00ffff', + 'aquamarine': '#7fffd4', + 'azure': '#f0ffff', + 'beige': '#f5f5dc', + 'bisque': '#ffe4c4', + 'black': '#000000', + 'blanchedalmond': '#ffebcd', + 'blue': '#0000ff', + 'blueviolet': '#8a2be2', + 'brown': '#a52a2a', + 'burlywood': '#deb887', + 'cadetblue': '#5f9ea0', + 'chartreuse': '#7fff00', + 'chocolate': '#d2691e', + 'coral': '#ff7f50', + 'cornflowerblue': '#6495ed', + 'cornsilk': '#fff8dc', + 'crimson': '#dc143c', + 'cyan': '#00ffff', + 'darkblue': '#00008b', + 'darkcyan': '#008b8b', + 'darkgoldenrod': '#b8860b', + 'darkgray': '#a9a9a9', + 'darkgrey': '#a9a9a9', + 'darkgreen': '#006400', + 'darkkhaki': '#bdb76b', + 'darkmagenta': '#8b008b', + 'darkolivegreen': '#556b2f', + 'darkorange': '#ff8c00', + 'darkorchid': '#9932cc', + 'darkred': '#8b0000', + 'darksalmon': '#e9967a', + 'darkseagreen': '#8fbc8f', + 'darkslateblue': '#483d8b', + 'darkslategray': '#2f4f4f', + 'darkslategrey': '#2f4f4f', + 'darkturquoise': '#00ced1', + 'darkviolet': '#9400d3', + 'deeppink': '#ff1493', + 'deepskyblue': '#00bfff', + 'dimgray': '#696969', + 'dimgrey': '#696969', + 'dodgerblue': '#1e90ff', + 'firebrick': '#b22222', + 'floralwhite': '#fffaf0', + 'forestgreen': '#228b22', + 'fuchsia': '#ff00ff', + 'gainsboro': '#dcdcdc', + 'ghostwhite': '#f8f8ff', + 'gold': '#ffd700', + 'goldenrod': '#daa520', + 'gray': '#808080', + 'grey': '#808080', + 'green': '#008000', + 'greenyellow': '#adff2f', + 'honeydew': '#f0fff0', + 'hotpink': '#ff69b4', + 'indianred ': '#cd5c5c', + 'indigo ': '#4b0082', + 'ivory': '#fffff0', + 'khaki': '#f0e68c', + 'lavender': '#e6e6fa', + 'lavenderblush': '#fff0f5', + 'lawngreen': '#7cfc00', + 'lemonchiffon': '#fffacd', + 'lightblue': '#add8e6', + 'lightcoral': '#f08080', + 'lightcyan': '#e0ffff', + 'lightgoldenrodyellow': '#fafad2', + 'lightgray': '#d3d3d3', + 'lightgrey': '#d3d3d3', + 'lightgreen': '#90ee90', + 'lightpink': '#ffb6c1', + 'lightsalmon': '#ffa07a', + 'lightseagreen': '#20b2aa', + 'lightskyblue': '#87cefa', + 'lightslategray': '#778899', + 'lightslategrey': '#778899', + 'lightsteelblue': '#b0c4de', + 'lightyellow': '#ffffe0', + 'lime': '#00ff00', + 'limegreen': '#32cd32', + 'linen': '#faf0e6', + 'magenta': '#ff00ff', + 'maroon': '#800000', + 'mediumaquamarine': '#66cdaa', + 'mediumblue': '#0000cd', + 'mediumorchid': '#ba55d3', + 'mediumpurple': '#9370db', + 'mediumseagreen': '#3cb371', + 'mediumslateblue': '#7b68ee', + 'mediumspringgreen': '#00fa9a', + 'mediumturquoise': '#48d1cc', + 'mediumvioletred': '#c71585', + 'midnightblue': '#191970', + 'mintcream': '#f5fffa', + 'mistyrose': '#ffe4e1', + 'moccasin': '#ffe4b5', + 'navajowhite': '#ffdead', + 'navy': '#000080', + 'oldlace': '#fdf5e6', + 'olive': '#808000', + 'olivedrab': '#6b8e23', + 'orange': '#ffa500', + 'orangered': '#ff4500', + 'orchid': '#da70d6', + 'palegoldenrod': '#eee8aa', + 'palegreen': '#98fb98', + 'paleturquoise': '#afeeee', + 'palevioletred': '#db7093', + 'papayawhip': '#ffefd5', + 'peachpuff': '#ffdab9', + 'peru': '#cd853f', + 'pink': '#ffc0cb', + 'plum': '#dda0dd', + 'powderblue': '#b0e0e6', + 'purple': '#800080', + 'rebeccapurple': '#663399', + 'red': '#ff0000', + 'rosybrown': '#bc8f8f', + 'royalblue': '#4169e1', + 'saddlebrown': '#8b4513', + 'salmon': '#fa8072', + 'sandybrown': '#f4a460', + 'seagreen': '#2e8b57', + 'seashell': '#fff5ee', + 'sienna': '#a0522d', + 'silver': '#c0c0c0', + 'skyblue': '#87ceeb', + 'slateblue': '#6a5acd', + 'slategray': '#708090', + 'slategrey': '#708090', + 'snow': '#fffafa', + 'springgreen': '#00ff7f', + 'steelblue': '#4682b4', + 'tan': '#d2b48c', + 'teal': '#008080', + 'thistle': '#d8bfd8', + 'tomato': '#ff6347', + 'turquoise': '#40e0d0', + 'violet': '#ee82ee', + 'wheat': '#f5deb3', + 'white': '#ffffff', + 'whitesmoke': '#f5f5f5', + 'yellow': '#ffff00', + 'yellowgreen': '#9acd32' }; function defaultTrueOption(value) { - return value === undefined ? true : value === true; + return value === undefined ? true : value === true; } function createMvcArray(array) { - if (!array) { - return new BaseArrayClass(); - } - if (array.type === "BaseArrayClass") { - return array; - } + if (!array) { + return new BaseArrayClass(); + } + if (array.type === 'BaseArrayClass') { + return array; + } - var mvcArray; - if (array.type === "LatLngBounds") { - array = [ - array.southwest, - {lat: array.northeast.lat, lng: array.southwest.lng}, - array.northeast, - {lat: array.southwest.lat, lng: array.northeast.lng}, - array.southwest - ]; - array = array.map(getLatLng); - } + var mvcArray; + if (array.type === 'LatLngBounds') { + array = [ + array.southwest, + { + lat: array.northeast.lat, + lng: array.southwest.lng + }, + array.northeast, + { + lat: array.southwest.lat, + lng: array.northeast.lng + }, + array.southwest + ]; + array = array.map(getLatLng); + } - if (array && typeof array.getArray === "function") { - mvcArray = new BaseArrayClass(array.getArray()); - array.on('set_at', function(index) { - var value = array.getAt(index); - value = "position" in value ? value.getPosition() : value; - mvcArray.setAt(index, value); - }); - array.on('insert_at', function(index) { - var value = array.getAt(index); - value = "position" in value ? value.getPosition() : value; - mvcArray.insertAt(index, value); - }); - array.on('remove_at', function(index) { - mvcArray.removeAt(index); - }); + if (array && typeof array.getArray === 'function') { + mvcArray = new BaseArrayClass(array.getArray()); + array.on('set_at', function (index) { + var value = array.getAt(index); + value = 'position' in value ? value.getPosition() : value; + mvcArray.setAt(index, value); + }); + array.on('insert_at', function (index) { + var value = array.getAt(index); + value = 'position' in value ? value.getPosition() : value; + mvcArray.insertAt(index, value); + }); + array.on('remove_at', function (index) { + mvcArray.removeAt(index); + }); - } else { - mvcArray = new BaseArrayClass(!!array ? array.slice(0) : undefined); - } - return mvcArray; + } else { + mvcArray = new BaseArrayClass(array ? array.slice(0) : undefined); + } + return mvcArray; } function getLatLng(target) { - return "getPosition" in target ? target.getPosition() : { - "lat": parseFloat(target.lat, 10), - "lng": parseFloat(target.lng, 10) + return 'getPosition' in target ? target.getPosition() : { + 'lat': parseFloat(target.lat, 10), + 'lng': parseFloat(target.lng, 10) }; } + function convertToPositionArray(array) { array = array || []; if (!utils.isArray(array)) { - if (array.type === "LatLngBounds") { + if (array.type === 'LatLngBounds') { array = [ array.southwest, - {lat: array.northeast.lat, lng: array.southwest.lng}, + { + lat: array.northeast.lat, + lng: array.southwest.lng + }, array.northeast, - {lat: array.southwest.lat, lng: array.northeast.lng}, + { + lat: array.southwest.lat, + lng: array.northeast.lng + }, array.southwest ]; - } else if (array && typeof array.getArray === "function") { + } else if (array && typeof array.getArray === 'function') { array = array.getArray(); } else { array = [array]; @@ -581,57 +585,57 @@ function markerOptionsFilter(markerOptions) { markerOptions.draggable = markerOptions.draggable === true; markerOptions.icon = markerOptions.icon || undefined; markerOptions.zIndex = markerOptions.zIndex || 0; - markerOptions.snippet = typeof(markerOptions.snippet) === "string" ? markerOptions.snippet : undefined; - markerOptions.title = typeof(markerOptions.title) === "string" ? markerOptions.title : undefined; + markerOptions.snippet = typeof (markerOptions.snippet) === 'string' ? markerOptions.snippet : undefined; + markerOptions.title = typeof (markerOptions.title) === 'string' ? markerOptions.title : undefined; markerOptions.visible = defaultTrueOption(markerOptions.visible); markerOptions.flat = markerOptions.flat === true; markerOptions.rotation = markerOptions.rotation || 0; - markerOptions.opacity = markerOptions.opacity === 0 ? 0 : (parseFloat("" + markerOptions.opacity, 10) || 1); + markerOptions.opacity = markerOptions.opacity === 0 ? 0 : (parseFloat('' + markerOptions.opacity, 10) || 1); markerOptions.disableAutoPan = markerOptions.disableAutoPan === true; markerOptions.noCache = markerOptions.noCache === true; //experimental - if (typeof markerOptions.icon === "object") { - if ("anchor" in markerOptions.icon && + if (typeof markerOptions.icon === 'object') { + if ('anchor' in markerOptions.icon && !Array.isArray(markerOptions.icon.anchor) && - "x" in markerOptions.icon.anchor && - "y" in markerOptions.icon.anchor) { + 'x' in markerOptions.icon.anchor && + 'y' in markerOptions.icon.anchor) { markerOptions.icon.anchor = [markerOptions.icon.anchor.x, markerOptions.icon.anchor.y]; } } - if ("infoWindowAnchor" in markerOptions && + if ('infoWindowAnchor' in markerOptions && !Array.isArray(markerOptions.infoWindowAnchor) && - "x" in markerOptions.infoWindowAnchor && - "y" in markerOptions.infoWindowAnchor) { + 'x' in markerOptions.infoWindowAnchor && + 'y' in markerOptions.infoWindowAnchor) { markerOptions.infoWindowAnchor = [markerOptions.infoWindowAnchor.x, markerOptions.infoWindowAnchor.anchor.y]; } - if ("style" in markerOptions && !("styles" in markerOptions)) { + if ('style' in markerOptions && !('styles' in markerOptions)) { markerOptions.styles = markerOptions.style; delete markerOptions.style; } - if ("styles" in markerOptions) { - markerOptions.styles = typeof markerOptions.styles === "object" ? markerOptions.styles : {}; + if ('styles' in markerOptions) { + markerOptions.styles = typeof markerOptions.styles === 'object' ? markerOptions.styles : {}; - if ("color" in markerOptions.styles) { - markerOptions.styles.color = HTMLColor2RGBA(markerOptions.styles.color || "#000000"); - } + if ('color' in markerOptions.styles) { + markerOptions.styles.color = HTMLColor2RGBA(markerOptions.styles.color || '#000000'); + } } if (markerOptions.icon && isHTMLColorString(markerOptions.icon)) { - markerOptions.icon = HTMLColor2RGBA(markerOptions.icon); + markerOptions.icon = HTMLColor2RGBA(markerOptions.icon); } if (markerOptions.icon && markerOptions.icon.label && isHTMLColorString(markerOptions.icon.label.color)) { - markerOptions.icon.label.color = HTMLColor2RGBA(markerOptions.icon.label.color); + markerOptions.icon.label.color = HTMLColor2RGBA(markerOptions.icon.label.color); } return markerOptions; } function quickfilter(domPositions, mapElemIDs) { - //console.log("before", JSON.parse(JSON.stringify(domPositions))); + //console.log('before', JSON.parse(JSON.stringify(domPositions))); var keys = Object.keys(domPositions); var tree = {}; - mapElemIDs.forEach(function(mapElemId) { + mapElemIDs.forEach(function (mapElemId) { var size = domPositions[mapElemId].size; var mapRect = { left: size.left, @@ -642,7 +646,7 @@ function quickfilter(domPositions, mapElemIDs) { tree[mapElemId] = domPositions[mapElemId]; - keys.forEach(function(elemId) { + keys.forEach(function (elemId) { if (domPositions[elemId].ignore) { return; } @@ -653,17 +657,17 @@ function quickfilter(domPositions, mapElemIDs) { bottom: domPositions[elemId].size.bottom + domPositions[elemId].size.height }; if ( - (domSize.left >= mapRect.left && domSize.left <= mapRect.right) || - (domSize.right >= mapRect.left && domSize.right <= mapRect.right) || - (domSize.top >= mapRect.top && domSize.top <= mapRect.bottom) || - (domSize.bottom >= mapRect.top && domSize.bottom <= mapRect.bottom) - ) { + (domSize.left >= mapRect.left && domSize.left <= mapRect.right) || + (domSize.right >= mapRect.left && domSize.right <= mapRect.right) || + (domSize.top >= mapRect.top && domSize.top <= mapRect.bottom) || + (domSize.bottom >= mapRect.top && domSize.bottom <= mapRect.bottom) + ) { tree[elemId] = domPositions[elemId]; } }); }); - //console.log("after", JSON.parse(JSON.stringify(tree))); + //console.log('after', JSON.parse(JSON.stringify(tree))); return tree; } @@ -672,14 +676,14 @@ function getPluginDomId(element) { if (!element || !shouldWatchByNative(element)) { return; } - var elemId = element.getAttribute("__pluginDomId"); + var elemId = element.getAttribute('__pluginDomId'); if (!elemId) { if (element === document.body) { - elemId = "root"; + elemId = 'root'; } else { - elemId = "pgm" + Math.floor(Math.random() * Date.now()); + elemId = 'pgm' + Math.floor(Math.random() * Date.now()); } - element.setAttribute("__pluginDomId", elemId); + element.setAttribute('__pluginDomId', elemId); } return elemId; } @@ -687,11 +691,12 @@ function getPluginDomId(element) { // Add hashCode() method // https://stackoverflow.com/a/7616484/697856 function hashCode(text) { - var hash = 0, i, chr; + var hash = 0, + i, chr; if (text.length === 0) return hash; for (i = 0; i < text.length; i++) { - chr = text.charCodeAt(i); - hash = ((hash << 5) - hash) + chr; + chr = text.charCodeAt(i); + hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; @@ -707,7 +712,7 @@ function createEvent(eventName, properties) { } else { evt = document.createEvent('Event'); evt.initEvent(eventName, true, false); - Object.keys(properties).forEach(function(key) { + Object.keys(properties).forEach(function (key) { if (!(key in properties)) { evt[key] = properties[key]; } @@ -717,30 +722,29 @@ function createEvent(eventName, properties) { } module.exports = { - _clearInternalCache: _clearInternalCache, - _removeCacheById: _removeCacheById, - getZIndex: getZIndex, - getDivRect: getDivRect, - getDomInfo: getDomInfo, - isDom: isDom, - parseBoolean: parseBoolean, - HLStoRGB: HLStoRGB, - HTMLColor2RGBA: HTMLColor2RGBA, - isHTMLColorString: isHTMLColorString, - defaultTrueOption: defaultTrueOption, - createMvcArray: createMvcArray, - getStyle: getStyle, - convertToPositionArray: convertToPositionArray, - getLatLng: getLatLng, - shouldWatchByNative: shouldWatchByNative, - markerOptionsFilter: markerOptionsFilter, - quickfilter: quickfilter, - nextTick: nextTick, - getPluginDomId: getPluginDomId, - hashCode: hashCode, - createEvent: createEvent + _clearInternalCache: _clearInternalCache, + _removeCacheById: _removeCacheById, + getZIndex: getZIndex, + getDivRect: getDivRect, + isDom: isDom, + parseBoolean: parseBoolean, + HLStoRGB: HLStoRGB, + HTMLColor2RGBA: HTMLColor2RGBA, + isHTMLColorString: isHTMLColorString, + defaultTrueOption: defaultTrueOption, + createMvcArray: createMvcArray, + getStyle: getStyle, + convertToPositionArray: convertToPositionArray, + getLatLng: getLatLng, + shouldWatchByNative: shouldWatchByNative, + markerOptionsFilter: markerOptionsFilter, + quickfilter: quickfilter, + nextTick: nextTick, + getPluginDomId: getPluginDomId, + hashCode: hashCode, + createEvent: createEvent }; -if (cordova && cordova.platformId === "browser") { +if (cordova && cordova.platformId === 'browser') { require('cordova/exec/proxy').add('common', module.exports); } diff --git a/www/Environment.js b/www/Environment.js index 5dbb205b6..059bb43b4 100644 --- a/www/Environment.js +++ b/www/Environment.js @@ -1,4 +1,3 @@ - var common = require('./Common'); /***************************************************************************** @@ -6,34 +5,32 @@ var common = require('./Common'); *****************************************************************************/ var Environment = {}; -Environment.setBackgroundColor = function(color) { - cordova.exec(null, null, 'PluginEnvironment', 'setBackGroundColor', [common.HTMLColor2RGBA(color)]); +Environment.setBackgroundColor = function (color) { + cordova.exec(null, null, 'PluginEnvironment', 'setBackGroundColor', [common.HTMLColor2RGBA(color)]); }; -Environment.isAvailable = function(callback) { - cordova.exec(function() { - if (typeof callback === "function") { - callback(true); - } - }, function(message) { - if (typeof callback === "function") { - callback(false, message); - } - }, 'PluginEnvironment', 'isAvailable', ['']); +Environment.isAvailable = function (callback) { + cordova.exec(function () { + if (typeof callback === 'function') { + callback(true); + } + }, function (message) { + if (typeof callback === 'function') { + callback(false, message); + } + }, 'PluginEnvironment', 'isAvailable', ['']); }; - -Environment.getLicenseInfo = function(callback) { - cordova.exec(function(txt) { - callback(txt); - }, null, 'PluginEnvironment', 'getLicenseInfo', []); +Environment.getLicenseInfo = function (callback) { + cordova.exec(function (txt) { + callback(txt); + }, null, 'PluginEnvironment', 'getLicenseInfo', []); }; -Environment.setEnv = function(options) { +Environment.setEnv = function (options) { if (options) { cordova.exec(null, null, 'PluginEnvironment', 'setEnv', [options]); } }; - module.exports = Environment; diff --git a/www/FusionTableOverlay.js b/www/FusionTableOverlay.js index e2da895d7..edeaf6cf1 100644 --- a/www/FusionTableOverlay.js +++ b/www/FusionTableOverlay.js @@ -1,5 +1,4 @@ -var argscheck = require('cordova/argscheck'), - utils = require('cordova/utils'), +var utils = require('cordova/utils'), common = require('./Common'), Overlay = require('./Overlay'); @@ -14,8 +13,8 @@ var FusionTableOverlay = function (map, FusionTableOverlayOptions, _exec) { //----------------------------------------------- // Sets event listeners //----------------------------------------------- - self.on("visible_changed", function () { - var visible = self.get("visible"); + self.on('visible_changed', function () { + var visible = self.get('visible'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setVisible', [self.getId(), visible]); }); }; @@ -23,7 +22,7 @@ var FusionTableOverlay = function (map, FusionTableOverlayOptions, _exec) { utils.extend(FusionTableOverlay, Overlay); FusionTableOverlay.prototype.getPluginName = function () { - return this.map.getId() + "-fusiontableoverlay"; + return this.map.getId() + '-fusiontableoverlay'; }; FusionTableOverlay.prototype.getHashCode = function () { @@ -47,17 +46,17 @@ FusionTableOverlay.prototype.getVisible = function () { FusionTableOverlay.prototype.remove = function (callback) { var self = this; if (self._isRemoved) { - if (typeof callback === "function") { + if (typeof callback === 'function') { return; } else { return Promise.resolve(); } } - Object.defineProperty(self, "_isRemoved", { + Object.defineProperty(self, '_isRemoved', { value: true, writable: false }); - self.trigger(self.id + "_remove"); + self.trigger(self.id + '_remove'); var resolver = function(resolve, reject) { self.exec.call(self, @@ -71,7 +70,7 @@ FusionTableOverlay.prototype.remove = function (callback) { }); }; - if (typeof callback === "function") { + if (typeof callback === 'function') { resolver(callback, self.errorHandler); } else { return new Promise(resolver); diff --git a/www/Geocoder.js b/www/Geocoder.js index cdcad611f..628b10000 100644 --- a/www/Geocoder.js +++ b/www/Geocoder.js @@ -1,76 +1,72 @@ - /***************************************************************************** +/***************************************************************************** * Geocoder class *****************************************************************************/ var common = require('./Common'), - BaseClass = require('./BaseClass'), utils = require('cordova/utils'); - -var Geocoder = function(exec) { +var Geocoder = function (exec) { return { - geocode: function(geocoderRequest, callback) { + geocode: function (geocoderRequest, callback) { geocoderRequest = geocoderRequest || {}; var requestProperty = null; - if ("position" in geocoderRequest && !("address" in geocoderRequest)) { - requestProperty = "position"; - } else if ("address" in geocoderRequest && !("position" in geocoderRequest)) { - requestProperty = "address"; + if ('position' in geocoderRequest && !('address' in geocoderRequest)) { + requestProperty = 'position'; + } else if ('address' in geocoderRequest && !('position' in geocoderRequest)) { + requestProperty = 'address'; } if (!requestProperty) { - var error = new Error("Invalid request"); - if (typeof callback === "function") { + var error = new Error('Invalid request'); + if (typeof callback === 'function') { callback([], error); } else { return Promise.reject(error); } } - if (geocoderRequest[requestProperty] instanceof Array || Array.isArray(geocoderRequest[requestProperty])) { //------------------------- // Geocoder.geocode({ // address: [ - // "Kyoto, Japan", - // "Tokyo, Japan" + // 'Kyoto, Japan', + // 'Tokyo, Japan' // ] // }) //------------------------- var mvcResults = common.createMvcArray(); - for (i = 0; i < requestCnt; i++) { + for (var i = 0; i < requestCnt; i++) { mvcResults.push(-1, true); } // Execute geocoder.geocode() when a new request is instearted. var requestCnt = geocoderRequest[requestProperty].length; var requests = common.createMvcArray(); - requests.on('insert_at', function(idx) { + requests.on('insert_at', function (idx) { var request = requests.getAt(idx); request.idx = idx; exec.call({ _isReady: true - }, function(result) { + }, function (result) { mvcResults.insertAt(result.idx, result.results); if (mvcResults.getLength() === requestCnt) { var tmp = mvcResults.getArray(); - var tmp2 = tmp.filter(function(ele) { + var tmp2 = tmp.filter(function (ele) { return ele === -1; }); if (tmp2.length === 0) { // Notifies `finish` event when all results are received. - mvcResults.trigger("finish"); + mvcResults.trigger('finish'); } } - }, function(error) { - mvcResults.trigger("error", error); - }, "PluginGeocoder", 'geocode', [request]); + }, function (error) { + mvcResults.trigger('error', error); + }, 'PluginGeocoder', 'geocode', [request]); }); - var request; var baseRequest = utils.clone(geocoderRequest); delete baseRequest[requestProperty]; @@ -78,13 +74,13 @@ var Geocoder = function(exec) { request = utils.clone(baseRequest); request[requestProperty] = geocoderRequest[requestProperty][i]; request.idx = i; - if (requestProperty === "position") { + if (requestProperty === 'position') { request.position.lat = request.position.lat || 0.0; request.position.lng = request.position.lng || 0.0; } requests.push(request); } - if (typeof callback === "function") { + if (typeof callback === 'function') { callback(mvcResults); } else { return Promise.resolve(mvcResults); @@ -92,23 +88,25 @@ var Geocoder = function(exec) { } else { //------------------------- // Geocoder.geocode({ - // address: "Kyoto, Japan" + // address: 'Kyoto, Japan' // }) //------------------------- - if (requestProperty === "position") { + if (requestProperty === 'position') { geocoderRequest.position.lat = geocoderRequest.position.lat || 0.0; geocoderRequest.position.lng = geocoderRequest.position.lng || 0.0; } geocoderRequest.idx = -1; - var resolver1 = function(resolve, reject) { - exec.call({_isReady: true}, function(_results) { + var resolver1 = function (resolve, reject) { + exec.call({ + _isReady: true + }, function (_results) { resolve(_results.results); - }, reject, "PluginGeocoder", 'geocode', [geocoderRequest]); + }, reject, 'PluginGeocoder', 'geocode', [geocoderRequest]); }; - if (typeof callback === "function") { - resolver1(callback, function(error) { + if (typeof callback === 'function') { + resolver1(callback, function (error) { callback([], error); }); } else { diff --git a/www/GroundOverlay.js b/www/GroundOverlay.js index c5fed83d4..6e2b0df4d 100644 --- a/www/GroundOverlay.js +++ b/www/GroundOverlay.js @@ -1,5 +1,4 @@ -var argscheck = require('cordova/argscheck'), - utils = require('cordova/utils'), +var utils = require('cordova/utils'), common = require('./Common'), Overlay = require('./Overlay'); @@ -20,32 +19,32 @@ var GroundOverlay = function (map, groundOverlayOptions, _exec) { //----------------------------------------------- // Sets event listeners //----------------------------------------------- - self.on("visible_changed", function () { - var visible = self.get("visible"); + self.on('visible_changed', function () { + var visible = self.get('visible'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setVisible', [self.getId(), visible]); }); - self.on("image_changed", function () { - var image = self.get("image"); + self.on('image_changed', function () { + var image = self.get('image'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setImage', [self.getId(), image]); }); - self.on("bounds_changed", function () { - var bounds = self.get("bounds"); + self.on('bounds_changed', function () { + var bounds = self.get('bounds'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setBounds', [self.getId(), bounds]); }); - self.on("opacity_changed", function () { - var opacity = self.get("opacity"); + self.on('opacity_changed', function () { + var opacity = self.get('opacity'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setOpacity', [self.getId(), opacity]); }); - self.on("clickable_changed", function () { - var clickable = self.get("clickable"); + self.on('clickable_changed', function () { + var clickable = self.get('clickable'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setClickable', [self.getId(), clickable]); }); - self.on("bearing_changed", function () { - var bearing = self.get("bearing"); + self.on('bearing_changed', function () { + var bearing = self.get('bearing'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setBearing', [self.getId(), bearing]); }); - self.on("zIndex_changed", function () { - var zIndex = self.get("zIndex"); + self.on('zIndex_changed', function () { + var zIndex = self.get('zIndex'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setZIndex', [self.getId(), zIndex]); }); @@ -70,19 +69,19 @@ GroundOverlay.prototype.setBounds = function (points) { bounds = []; for (i = 0; i < points.length; i++) { bounds.push({ - "lat": parseFloat(points[i].lat, 10), - "lng": parseFloat(points[i].lng, 10) + 'lat': parseFloat(points[i].lat, 10), + 'lng': parseFloat(points[i].lng, 10) }); } this.set('bounds', bounds); }; GroundOverlay.prototype.getOpacity = function () { - return this.get("opacity"); + return this.get('opacity'); }; GroundOverlay.prototype.getBearing = function () { - return this.get("bearing"); + return this.get('bearing'); }; GroundOverlay.prototype.setOpacity = function (opacity) { @@ -100,7 +99,7 @@ GroundOverlay.prototype.setBearing = function (bearing) { }; GroundOverlay.prototype.getZIndex = function () { - return this.get("zIndex"); + return this.get('zIndex'); }; GroundOverlay.prototype.setZIndex = function (zIndex) { @@ -118,17 +117,17 @@ GroundOverlay.prototype.getClickable = function () { GroundOverlay.prototype.remove = function (callback) { var self = this; if (self._isRemoved) { - if (typeof callback === "function") { + if (typeof callback === 'function') { return; } else { return Promise.resolve(); } } - Object.defineProperty(self, "_isRemoved", { + Object.defineProperty(self, '_isRemoved', { value: true, writable: false }); - self.trigger(self.id + "_remove"); + self.trigger(self.id + '_remove'); var resolver = function(resolve, reject) { self.exec.call(self, @@ -142,7 +141,7 @@ GroundOverlay.prototype.remove = function (callback) { }); }; - if (typeof callback === "function") { + if (typeof callback === 'function') { resolver(callback, self.errorHandler); } else { return new Promise(resolver); diff --git a/www/HtmlInfoWindow.js b/www/HtmlInfoWindow.js index 8c3b0c612..e73aa4df7 100644 --- a/www/HtmlInfoWindow.js +++ b/www/HtmlInfoWindow.js @@ -1,7 +1,6 @@ - var utils = require('cordova/utils'), +var utils = require('cordova/utils'), event = require('./event'), - common = require('./Common'), BaseClass = require('./BaseClass'); /***************************************************************************** @@ -25,7 +24,7 @@ var HTMLInfoWindow = function () { target.on.call(target, eventName, callback); }, bindTo: function (srcObj, srcField, dstObj, dstField, noNotify) { - var eventName = srcField + "_changed"; + var eventName = srcField + '_changed'; dstField = dstField || srcField; var callback = function (oldValue, newValue) { dstObj.set(dstField, newValue, noNotify); @@ -48,184 +47,184 @@ var HTMLInfoWindow = function () { } }; - Object.defineProperty(self, "_hook", { + Object.defineProperty(self, '_hook', { value: listenerMgr, writable: false }); - var frame = document.createElement("div"); - frame.style.overflow = "visible"; - frame.style.position = "absolute"; - frame.style.display = "inline-block"; + var frame = document.createElement('div'); + frame.style.overflow = 'visible'; + frame.style.position = 'absolute'; + frame.style.display = 'inline-block'; frame.classList.add('pgm-html-info-frame'); - self.set("frame", frame); + self.set('frame', frame); - var anchorDiv = document.createElement("div"); - anchorDiv.setAttribute("class", "pgm-anchor"); - anchorDiv.style.overflow = "visible"; - anchorDiv.style.position = "absolute"; - anchorDiv.style["z-index"] = 0; - anchorDiv.style.width = "0 !important"; - anchorDiv.style.height = "0 !important"; - //anchorDiv.style.border = "1px solid green"; - //anchorDiv.style.backgroundColor = "rgba(125, 125, 255, 0.5)"; + var anchorDiv = document.createElement('div'); + anchorDiv.setAttribute('class', 'pgm-anchor'); + anchorDiv.style.overflow = 'visible'; + anchorDiv.style.position = 'absolute'; + anchorDiv.style['z-index'] = 0; + anchorDiv.style.width = '0 !important'; + anchorDiv.style.height = '0 !important'; + //anchorDiv.style.border = '1px solid green'; + //anchorDiv.style.backgroundColor = 'rgba(125, 125, 255, 0.5)'; - anchorDiv.style.transition = "transform 0s ease"; - anchorDiv.style['will-change'] = "transform"; + anchorDiv.style.transition = 'transform 0s ease'; + anchorDiv.style['will-change'] = 'transform'; anchorDiv.style['-webkit-backface-visibility'] = 'hidden'; anchorDiv.style['-webkit-perspective'] = 1000; - anchorDiv.style['-webkit-transition'] = "-webkit-transform 0s ease"; + anchorDiv.style['-webkit-transition'] = '-webkit-transform 0s ease'; anchorDiv.appendChild(frame); - self.set("anchor", anchorDiv); + self.set('anchor', anchorDiv); - var contentBox = document.createElement("div"); - contentBox.style.display = "inline-block"; - contentBox.style.padding = "5px"; - contentBox.style.boxSizing = "content-box"; + var contentBox = document.createElement('div'); + contentBox.style.display = 'inline-block'; + contentBox.style.padding = '5px'; + contentBox.style.boxSizing = 'content-box'; contentBox.classList.add('pgm-html-info-content-box'); - var contentFrame = document.createElement("div"); - contentFrame.style.display = "block"; - contentFrame.style.position = "relative"; - contentFrame.style.backgroundColor = "white"; - contentFrame.style.border = "1px solid rgb(204, 204, 204)"; - contentFrame.style.left = "0px"; - contentFrame.style.right = "0px"; - contentFrame.style.zIndex = "1"; // In order to set higher depth than the map div certainly - contentFrame.style.overflow = "hidden"; + var contentFrame = document.createElement('div'); + contentFrame.style.display = 'block'; + contentFrame.style.position = 'relative'; + contentFrame.style.backgroundColor = 'white'; + contentFrame.style.border = '1px solid rgb(204, 204, 204)'; + contentFrame.style.left = '0px'; + contentFrame.style.right = '0px'; + contentFrame.style.zIndex = '1'; // In order to set higher depth than the map div certainly + contentFrame.style.overflow = 'hidden'; contentFrame.classList.add('pgm-html-info-content-frame'); frame.appendChild(contentFrame); contentFrame.appendChild(contentBox); - var tailFrame = document.createElement("div"); - tailFrame.style.position = "relative"; - tailFrame.style.top = "-1px"; + var tailFrame = document.createElement('div'); + tailFrame.style.position = 'relative'; + tailFrame.style.top = '-1px'; tailFrame.style.zIndex = 100; tailFrame.classList.add('pgm-html-info-tail-frame'); frame.appendChild(tailFrame); - var tailLeft = document.createElement("div"); + var tailLeft = document.createElement('div'); /* - tailLeft.style.position = "absolute"; - tailLeft.style.marginLeft = "-15px"; - tailLeft.style.left = "50%"; - tailLeft.style.top = "0px"; - tailLeft.style.height = "15px"; - tailLeft.style.width = "16px"; - tailLeft.style.overflow = "hidden"; - tailLeft.style.borderWidth = "0px"; + tailLeft.style.position = 'absolute'; + tailLeft.style.marginLeft = '-15px'; + tailLeft.style.left = '50%'; + tailLeft.style.top = '0px'; + tailLeft.style.height = '15px'; + tailLeft.style.width = '16px'; + tailLeft.style.overflow = 'hidden'; + tailLeft.style.borderWidth = '0px'; */ tailLeft.classList.add('pgm-html-info-tail-left'); - tailLeft.style.position = "absolute"; - tailLeft.style.left = "50%"; - tailLeft.style.height = "0px"; - tailLeft.style.width = "0px"; - tailLeft.style.marginLeft = "-15px"; - tailLeft.style.borderWidth = "15px 15px 0px"; - tailLeft.style.borderColor = "rgb(204, 204, 204) transparent transparent"; - tailLeft.style.borderStyle = "solid"; + tailLeft.style.position = 'absolute'; + tailLeft.style.left = '50%'; + tailLeft.style.height = '0px'; + tailLeft.style.width = '0px'; + tailLeft.style.marginLeft = '-15px'; + tailLeft.style.borderWidth = '15px 15px 0px'; + tailLeft.style.borderColor = 'rgb(204, 204, 204) transparent transparent'; + tailLeft.style.borderStyle = 'solid'; tailFrame.appendChild(tailLeft); /* - var tailLeftCover = document.createElement("div"); - tailLeftCover.style.position = "absolute"; - tailLeftCover.style.backgroundColor = "white"; - tailLeftCover.style.transform = "skewX(45deg)"; - tailLeftCover.style.transformOrigin = "0px 0px 0px"; - tailLeftCover.style.left = "0px"; - tailLeftCover.style.height = "15px"; - tailLeftCover.style.width = "15px"; - tailLeftCover.style.top = "0px"; + var tailLeftCover = document.createElement('div'); + tailLeftCover.style.position = 'absolute'; + tailLeftCover.style.backgroundColor = 'white'; + tailLeftCover.style.transform = 'skewX(45deg)'; + tailLeftCover.style.transformOrigin = '0px 0px 0px'; + tailLeftCover.style.left = '0px'; + tailLeftCover.style.height = '15px'; + tailLeftCover.style.width = '15px'; + tailLeftCover.style.top = '0px'; tailLeftCover.style.zIndex = 1; - tailLeftCover.style.borderLeft = "1px solid rgb(204, 204, 204)"; + tailLeftCover.style.borderLeft = '1px solid rgb(204, 204, 204)'; tailLeft.classList.add('pgm-html-info-tail-left-cover'); tailLeft.appendChild(tailLeftCover); */ - var tailRight = document.createElement("div"); + var tailRight = document.createElement('div'); /* - tailRight.style.position = "absolute"; - tailRight.style.left = "50%"; - tailRight.style.top = "0px"; - tailRight.style.height = "15px"; - tailRight.style.width = "16px"; - tailRight.style.overflow = "hidden"; - tailRight.style.borderWidth = "0px"; + tailRight.style.position = 'absolute'; + tailRight.style.left = '50%'; + tailRight.style.top = '0px'; + tailRight.style.height = '15px'; + tailRight.style.width = '16px'; + tailRight.style.overflow = 'hidden'; + tailRight.style.borderWidth = '0px'; */ - tailRight.style.position = "absolute"; - tailRight.style.left = "50%"; - tailRight.style.height = "0px"; - tailRight.style.width = "0px"; - tailRight.style.marginLeft = "-14px"; - tailRight.style.borderTopWidth = "14px"; - tailRight.style.borderLeftWidth = "14px"; - tailRight.style.borderRightWidth = "14px"; - tailRight.style.borderColor = "rgb(255, 255, 255) transparent transparent"; - tailRight.style.borderStyle = "solid"; + tailRight.style.position = 'absolute'; + tailRight.style.left = '50%'; + tailRight.style.height = '0px'; + tailRight.style.width = '0px'; + tailRight.style.marginLeft = '-14px'; + tailRight.style.borderTopWidth = '14px'; + tailRight.style.borderLeftWidth = '14px'; + tailRight.style.borderRightWidth = '14px'; + tailRight.style.borderColor = 'rgb(255, 255, 255) transparent transparent'; + tailRight.style.borderStyle = 'solid'; tailRight.classList.add('pgm-html-info-tail-right'); tailFrame.appendChild(tailRight); /* - var tailRightCover = document.createElement("div"); - tailRightCover.style.position = "absolute"; - tailRightCover.style.backgroundColor = "white"; - tailRightCover.style.transform = "skewX(-45deg)"; - tailRightCover.style.transformOrigin = "0px 0px 0px"; - tailRightCover.style.left = "0px"; - tailRightCover.style.height = "15px"; - tailRightCover.style.width = "15px"; - tailRightCover.style.top = "0px"; + var tailRightCover = document.createElement('div'); + tailRightCover.style.position = 'absolute'; + tailRightCover.style.backgroundColor = 'white'; + tailRightCover.style.transform = 'skewX(-45deg)'; + tailRightCover.style.transformOrigin = '0px 0px 0px'; + tailRightCover.style.left = '0px'; + tailRightCover.style.height = '15px'; + tailRightCover.style.width = '15px'; + tailRightCover.style.top = '0px'; tailRightCover.style.zIndex = 2; - tailRightCover.style.borderRight = "1px solid rgb(204, 204, 204)"; + tailRightCover.style.borderRight = '1px solid rgb(204, 204, 204)'; tailRightCover.classList.add('pgm-html-info-tail-right-cover'); tailRight.appendChild(tailRightCover); */ - var eraseBorder = document.createElement("div"); - eraseBorder.style.position = "absolute"; + var eraseBorder = document.createElement('div'); + eraseBorder.style.position = 'absolute'; eraseBorder.style.zIndex = 3; - eraseBorder.style.backgroundColor = "white"; - eraseBorder.style.width = "27px"; - eraseBorder.style.height = "2px"; - eraseBorder.style.top = "-1px"; - eraseBorder.style.left = "50%"; - eraseBorder.style.marginLeft = "-13px"; + eraseBorder.style.backgroundColor = 'white'; + eraseBorder.style.width = '27px'; + eraseBorder.style.height = '2px'; + eraseBorder.style.top = '-1px'; + eraseBorder.style.left = '50%'; + eraseBorder.style.marginLeft = '-13px'; eraseBorder.classList.add('pgm-html-info-tail-erase-border'); tailFrame.appendChild(eraseBorder); var calculate = function (marker) { - //var marker = self.get("marker"); + //var marker = self.get('marker'); var map = marker.getMap(); var div = map.getDiv(); - var frame = self.get("frame"); + var frame = self.get('frame'); var contentFrame = frame.firstChild; var contentBox = contentFrame.firstChild; - contentBox.style.minHeight = "50px"; - contentBox.style.width = "auto"; - contentBox.style.height = "auto"; - contentBox.style.padding = "5px"; - - var content = self.get("content"); - if (typeof content === "string") { - contentBox.style.whiteSpace = "pre-wrap"; + contentBox.style.minHeight = '50px'; + contentBox.style.width = 'auto'; + contentBox.style.height = 'auto'; + contentBox.style.padding = '5px'; + + var content = self.get('content'); + if (typeof content === 'string') { + contentBox.style.whiteSpace = 'pre-wrap'; contentBox.innerHTML = content; } else { if (!content) { - contentBox.innerText = ""; + contentBox.innerText = ''; } else if (content.nodeType === 1) { - contentBox.innerHTML = ""; + contentBox.innerHTML = ''; contentBox.appendChild(content); } else { contentBox.innerText = content; } } - var cssOptions = self.get("cssOptions"); - if (cssOptions && typeof cssOptions === "object") { + var cssOptions = self.get('cssOptions'); + if (cssOptions && typeof cssOptions === 'object') { var keys = Object.keys(cssOptions); keys.forEach(function (key) { contentBox.style.setProperty(key, cssOptions[key]); @@ -239,19 +238,19 @@ var HTMLInfoWindow = function () { // Adjust the HTMLInfoWindow size var contentsWidth = contentBox.offsetWidth + 10; // padding 5px x 2 var contentsHeight = contentBox.offsetHeight; - self.set("contentsHeight", contentsHeight); - contentFrame.style.width = contentsWidth + "px"; - contentFrame.style.height = contentsHeight + "px"; - frame.style.width = contentsWidth + "px"; - frame.style.height = (contentsHeight + 15) + "px"; + self.set('contentsHeight', contentsHeight); + contentFrame.style.width = contentsWidth + 'px'; + contentFrame.style.height = contentsHeight + 'px'; + frame.style.width = contentsWidth + 'px'; + frame.style.height = (contentsHeight + 15) + 'px'; if (contentBox.offsetWidth > div.offsetWidth * 0.9) { - contentBox.style.width = (div.offsetWidth * 0.9) + "px"; + contentBox.style.width = (div.offsetWidth * 0.9) + 'px'; } - contentBox.style.width = "100%"; - contentBox.style.height = "100%"; - contentBox.style.padding = "5px 17px 17px 5px"; - self.set("contentsWidth", contentsWidth); + contentBox.style.width = '100%'; + contentBox.style.height = '100%'; + contentBox.style.padding = '5px 17px 17px 5px'; + self.set('contentsWidth', contentsWidth); var infoOffset = { x: 31, @@ -270,16 +269,16 @@ var HTMLInfoWindow = function () { y: 15 }; - var icon = marker.get("icon"); + var icon = marker.get('icon'); - if (typeof icon === "object") { - if (typeof icon.url === "string" && icon.url.indexOf("data:image/") === 0) { - var img = document.createElement("img"); + if (typeof icon === 'object') { + if (typeof icon.url === 'string' && icon.url.indexOf('data:image/') === 0) { + var img = document.createElement('img'); img.src = icon.url; iconSize.width = img.width; iconSize.height = img.height; } - if (typeof icon.size === "object") { + if (typeof icon.size === 'object') { iconSize.width = icon.size.width; iconSize.height = icon.size.height; } @@ -290,7 +289,7 @@ var HTMLInfoWindow = function () { } } - var infoWindowAnchor = marker.get("infoWindowAnchor"); + var infoWindowAnchor = marker.get('infoWindowAnchor'); if (utils.isArray(infoWindowAnchor)) { infoOffset.x = infoWindowAnchor[0]; infoOffset.y = infoWindowAnchor[1]; @@ -313,113 +312,113 @@ var HTMLInfoWindow = function () { anchor.y *= iconSize.height; anchor.x *= iconSize.width; - //console.log("contentsSize = " + contentsWidth + ", " + contentsHeight); - //console.log("iconSize = " + iconSize.width + ", " + iconSize.height); - //console.log("infoOffset = " + infoOffset.x + ", " + infoOffset.y); + //console.log('contentsSize = ' + contentsWidth + ', ' + contentsHeight); + //console.log('iconSize = ' + iconSize.width + ', ' + iconSize.height); + //console.log('infoOffset = ' + infoOffset.x + ', ' + infoOffset.y); - var frameBorder = parseInt(common.getStyle(contentFrame, "border-left-width").replace(/[^\d]/g, ""), 10); + //var frameBorder = parseInt(common.getStyle(contentFrame, 'border-left-width').replace(/[^\d]/g, ''), 10); //var offsetX = (contentsWidth + frameBorder + anchor.x ) * 0.5 + (iconSize.width / 2 - infoOffset.x); //var offsetY = contentsHeight + anchor.y - (frameBorder * 2) - infoOffset.y + 15; - var offsetX = -(iconSize.width / 2) - (cordova.platformId === "android" ? 1 : 0); - var offsetY = -iconSize.height - (cordova.platformId === "android" ? 1 : 0); - anchorDiv.style.width = iconSize.width + "px"; - anchorDiv.style.height = iconSize.height + "px"; - - self.set("offsetX", offsetX); - self.set("offsetY", offsetY); - - frame.style.bottom = (iconSize.height - infoOffset.y) + "px"; - frame.style.left = ((-contentsWidth) / 2 + infoOffset.x) + "px"; - - //console.log("frameLeft = " + frame.style.left ); - var point = map.get("infoPosition"); - anchorDiv.style.visibility = "hidden"; - var x = point.x + self.get("offsetX"); - var y = point.y + self.get("offsetY"); - anchorDiv.style['-webkit-transform'] = "translate3d(" + x + "px, " + y + "px, 0px)"; - anchorDiv.style.transform = "translate3d(" + x + "px, " + y + "px, 0px)"; - anchorDiv.style.visibility = "visible"; - self.trigger("infoPosition_changed", "", point); + var offsetX = -(iconSize.width / 2) - (cordova.platformId === 'android' ? 1 : 0); + var offsetY = -iconSize.height - (cordova.platformId === 'android' ? 1 : 0); + anchorDiv.style.width = iconSize.width + 'px'; + anchorDiv.style.height = iconSize.height + 'px'; + + self.set('offsetX', offsetX); + self.set('offsetY', offsetY); + + frame.style.bottom = (iconSize.height - infoOffset.y) + 'px'; + frame.style.left = ((-contentsWidth) / 2 + infoOffset.x) + 'px'; + + //console.log('frameLeft = ' + frame.style.left ); + var point = map.get('infoPosition'); + anchorDiv.style.visibility = 'hidden'; + var x = point.x + self.get('offsetX'); + var y = point.y + self.get('offsetY'); + anchorDiv.style['-webkit-transform'] = 'translate3d(' + x + 'px, ' + y + 'px, 0px)'; + anchorDiv.style.transform = 'translate3d(' + x + 'px, ' + y + 'px, 0px)'; + anchorDiv.style.visibility = 'visible'; + self.trigger('infoPosition_changed', '', point); self.trigger(event.INFO_OPEN); }; - self._hook.on(self, "infoPosition_changed", function (ignore, point) { + self._hook.on(self, 'infoPosition_changed', function (ignore, point) { if (!point) return; - var x = point.x + self.get("offsetX"); - var y = point.y + self.get("offsetY"); - anchorDiv.style['-webkit-transform'] = "translate3d(" + x + "px, " + y + "px, 0px)"; - anchorDiv.style.transform = "translate3d(" + x + "px, " + y + "px, 0px)"; + var x = point.x + self.get('offsetX'); + var y = point.y + self.get('offsetY'); + anchorDiv.style['-webkit-transform'] = 'translate3d(' + x + 'px, ' + y + 'px, 0px)'; + anchorDiv.style.transform = 'translate3d(' + x + 'px, ' + y + 'px, 0px)'; }); - self._hook.on(self, "infoWindowAnchor_changed", calculate); + self._hook.on(self, 'infoWindowAnchor_changed', calculate); - self.set("isInfoWindowVisible", false); + self.set('isInfoWindowVisible', false); }; utils.extend(HTMLInfoWindow, BaseClass); HTMLInfoWindow.prototype.isInfoWindowShown = function () { - return this.get("isInfoWindowVisible") === true; + return this.get('isInfoWindowVisible') === true; }; HTMLInfoWindow.prototype.close = function () { var self = this; - var marker = self.get("marker"); + var marker = self.get('marker'); if (marker) { - self._hook.off(marker, "isInfoWindowVisible_changed"); + self._hook.off(marker, 'isInfoWindowVisible_changed'); } if (!self.isInfoWindowShown() || !marker) { return; } - self.set("isInfoWindowVisible", false); - marker.set("isInfoWindowVisible", false); - marker.set("infoWindow", undefined); + self.set('isInfoWindowVisible', false); + marker.set('isInfoWindowVisible', false); + marker.set('infoWindow', undefined); this.set('marker', undefined); var map = marker.getMap(); - self._hook.off(marker.getMap(), "map_clear"); - self._hook.off(marker, "infoPosition_changed"); - self._hook.off(marker, "icon_changed"); - //self._hook.off(self, "infoWindowAnchor_changed"); + self._hook.off(marker.getMap(), 'map_clear'); + self._hook.off(marker, 'infoPosition_changed'); + self._hook.off(marker, 'icon_changed'); + //self._hook.off(self, 'infoWindowAnchor_changed'); self._hook.off(marker, event.INFO_CLOSE); //This event listener is assigned in the open method. So detach it. self.trigger(event.INFO_CLOSE); - map.set("active_marker", null); + map.set('active_marker', null); //var div = map.getDiv(); - var anchorDiv = self.get("anchor"); + var anchorDiv = self.get('anchor'); if (anchorDiv && anchorDiv.parentNode) { anchorDiv.parentNode.removeChild(anchorDiv); // Remove the contents from this HTMLInfoWindow var contentFrame = anchorDiv.firstChild.firstChild; var contentBox = contentFrame.firstChild; - contentBox.innerHTML = ""; + contentBox.innerHTML = ''; } }; HTMLInfoWindow.prototype.setContent = function (content, cssOptions) { var self = this; - var prevContent = self.get("content"); - self.set("content", content); - self.set("cssOptions", cssOptions); - var marker = self.get("marker"); + var prevContent = self.get('content'); + self.set('content', content); + self.set('cssOptions', cssOptions); + var marker = self.get('marker'); if (content !== prevContent && marker && marker.isInfoWindowShown()) { - var anchorDiv = self.get("anchor"); + var anchorDiv = self.get('anchor'); if (anchorDiv) { - anchorDiv.style.width = "0 !important"; - anchorDiv.style.height = "0 !important"; + anchorDiv.style.width = '0 !important'; + anchorDiv.style.height = '0 !important'; if (anchorDiv.parentNode) { anchorDiv.parentNode.removeChild(anchorDiv); // Remove the contents from this HTMLInfoWindow var contentFrame = anchorDiv.firstChild.firstChild; var contentBox = contentFrame.firstChild; - contentBox.innerHTML = ""; + contentBox.innerHTML = ''; } } - self.trigger("infoWindowAnchor_changed", marker); + self.trigger('infoWindowAnchor_changed', marker); } }; @@ -432,44 +431,43 @@ HTMLInfoWindow.prototype.open = function (marker) { marker = marker._objectInstance; } - var map = marker.getMap(); var self = this, - markerId = marker.getId(); + map = marker.getMap(); - marker.set("infoWindow", self); - marker.set("isInfoWindowVisible", true); - self._hook.on(marker, "icon_changed", function () { - self.trigger.call(self, "infoWindowAnchor_changed", marker); + marker.set('infoWindow', self); + marker.set('isInfoWindowVisible', true); + self._hook.on(marker, 'icon_changed', function () { + self.trigger.call(self, 'infoWindowAnchor_changed', marker); }); - self.set("isInfoWindowVisible", true); - self._hook.on(marker, "isInfoWindowVisible_changed", function (prevValue, newValue) { + self.set('isInfoWindowVisible', true); + self._hook.on(marker, 'isInfoWindowVisible_changed', function (prevValue, newValue) { if (newValue === false) { self.close.call(self); } }); map.fromLatLngToPoint(marker.getPosition(), function (point) { - map.set("infoPosition", { + map.set('infoPosition', { x: point[0], y: point[1] }); - self._hook.bindTo(map, "infoPosition", self); - self._hook.bindTo(marker, "infoWindowAnchor", self); - self._hook.bindTo(marker, "icon", self); - self._hook.one(marker.getMap(), "map_clear", self.close.bind(self)); + self._hook.bindTo(map, 'infoPosition', self); + self._hook.bindTo(marker, 'infoWindowAnchor', self); + self._hook.bindTo(marker, 'icon', self); + self._hook.one(marker.getMap(), 'map_clear', self.close.bind(self)); self._hook.one(marker, event.INFO_CLOSE, self.close.bind(self)); - self.set("marker", marker); - map.set("active_marker", marker); - self.trigger.call(self, "infoWindowAnchor_changed", marker); + self.set('marker', marker); + map.set('active_marker', marker); + self.trigger.call(self, 'infoWindowAnchor_changed', marker); }); }; HTMLInfoWindow.prototype.setBackgroundColor = function (backgroundColor) { - this.get("frame").children[0].style.backgroundColor = backgroundColor; - this.get("frame").children[1].children[0].style.borderColor = backgroundColor + " rgba(0,0,0,0) rgba(0,0,0,0)"; - this.get("frame").children[1].children[1].style.borderColor = backgroundColor + " rgba(0,0,0,0) rgba(0,0,0,0)"; - this.get("frame").children[1].children[2].style.backgroundColor = backgroundColor; + this.get('frame').children[0].style.backgroundColor = backgroundColor; + this.get('frame').children[1].children[0].style.borderColor = backgroundColor + ' rgba(0,0,0,0) rgba(0,0,0,0)'; + this.get('frame').children[1].children[1].style.borderColor = backgroundColor + ' rgba(0,0,0,0) rgba(0,0,0,0)'; + this.get('frame').children[1].children[2].style.backgroundColor = backgroundColor; }; module.exports = HTMLInfoWindow; diff --git a/www/InlineWorker.js b/www/InlineWorker.js index 010e5ff40..a969efece 100644 --- a/www/InlineWorker.js +++ b/www/InlineWorker.js @@ -26,7 +26,7 @@ function InlineWorker(func, self) { )[1]; return new global.Worker(global.URL.createObjectURL( - new global.Blob([ functionBody ], { type: "text/javascript" }) + new global.Blob([ functionBody ], { type: 'text/javascript' }) )); } diff --git a/www/KmlLoader.js b/www/KmlLoader.js index d77522569..3b4dc6482 100644 --- a/www/KmlLoader.js +++ b/www/KmlLoader.js @@ -1,79 +1,73 @@ - - - -var argscheck = require('cordova/argscheck'), - utils = require('cordova/utils'), - common = require('./Common'), - event = require('./event'), - BaseClass = require('./BaseClass'), - BaseArrayClass = require('./BaseArrayClass'), - LatLngBounds = require('./LatLngBounds'), - VisibleRegion = require('./VisibleRegion'); +var utils = require('cordova/utils'), + event = require('./event'), + BaseClass = require('./BaseClass'), + BaseArrayClass = require('./BaseArrayClass'), + VisibleRegion = require('./VisibleRegion'); /***************************************************************************** * KmlLoader Class *****************************************************************************/ -var KmlLoader = function(map, exec, options) { +var KmlLoader = function (map, exec, options) { BaseClass.apply(this); var self = this; - //self.set("visible", KmlLoaderOptions.visible === undefined ? true : KmlLoaderOptions.visible); - //self.set("zIndex", KmlLoaderOptions.zIndex || 0); - Object.defineProperty(self, "_overlays", { - value: new BaseArrayClass(), - writable: false + //self.set('visible', KmlLoaderOptions.visible === undefined ? true : KmlLoaderOptions.visible); + //self.set('zIndex', KmlLoaderOptions.zIndex || 0); + Object.defineProperty(self, '_overlays', { + value: new BaseArrayClass(), + writable: false }); - Object.defineProperty(self, "_isReady", { - value: true, - writable: false + Object.defineProperty(self, '_isReady', { + value: true, + writable: false }); - Object.defineProperty(self, "type", { - value: "KmlLoader", - writable: false + Object.defineProperty(self, 'type', { + value: 'KmlLoader', + writable: false }); - Object.defineProperty(self, "map", { - value: map, - writable: false + Object.defineProperty(self, 'map', { + value: map, + writable: false }); - Object.defineProperty(self, "exec", { - value: exec, - writable: false + Object.defineProperty(self, 'exec', { + value: exec, + writable: false }); - Object.defineProperty(self, "options", { - value: options, - writable: false + Object.defineProperty(self, 'options', { + value: options, + writable: false }); - Object.defineProperty(self, "kmlUrl", { - value: options.url, - writable: false + Object.defineProperty(self, 'kmlUrl', { + value: options.url, + writable: false }); - Object.defineProperty(self, "camera", { - value: { - target: [] - }, - writable: false + Object.defineProperty(self, 'camera', { + value: { + target: [] + }, + writable: false }); }; utils.extend(KmlLoader, BaseClass); -KmlLoader.prototype.parseKmlFile = function(callback) { +KmlLoader.prototype.parseKmlFile = function (callback, errorCallback) { var self = this; - self.exec.call(self.map, function(kmlData) { - var rawKmlData = JSON.parse(JSON.stringify(kmlData)); -//console.log(rawKmlData); - Object.defineProperty(self, "kmlStyles", { + self.exec.call(self.map, function (kmlData) { + //var rawKmlData = JSON.parse(JSON.stringify(kmlData)); + //console.log(rawKmlData); + Object.defineProperty(self, 'kmlStyles', { value: kmlData.styles, writable: false }); - Object.defineProperty(self, "kmlSchemas", { + Object.defineProperty(self, 'kmlSchemas', { value: kmlData.schemas, writable: false }); var placeMarks = new BaseArrayClass(kmlData.root.children); - placeMarks.mapAsync(function(placeMark, cb) { + placeMarks.mapAsync(function (placeMark, cb) { self.kmlTagProcess.call(self, { child: placeMark, attrHolder: {}, @@ -81,20 +75,22 @@ KmlLoader.prototype.parseKmlFile = function(callback) { children: [] } }, cb); - }, function(placeMarkOverlays) { - placeMarkOverlays = placeMarkOverlays.filter(function(overlay) { + }, function (placeMarkOverlays) { + placeMarkOverlays = placeMarkOverlays.filter(function (overlay) { return !!overlay; }); var result = placeMarkOverlays.shift(); //result.set('kmlData', rawKmlData); callback.call(self, self.camera, result); }); - }, self.map.errorHandler, self.map.id, 'loadPlugin', ['KmlOverlay', { + }, errorCallback, self.map.id, 'loadPlugin', ['KmlOverlay', { url: self.options.url - }], {sync: true}); + }], { + sync: true + }); }; -KmlLoader.prototype.kmlTagProcess = function(params, callback) { +KmlLoader.prototype.kmlTagProcess = function (params, callback) { var self = this; if (params.child.styleIDs) { @@ -102,19 +98,19 @@ KmlLoader.prototype.kmlTagProcess = function(params, callback) { // Read styles if specified //--------------------------- var styleIDs = new BaseArrayClass(params.child.styleIDs); - styleIDs.mapAsync(function(styleId, cb) { + styleIDs.mapAsync(function (styleId, cb) { self.getStyleById.call(self, styleId, cb); - }, function(styleSets) { + }, function (styleSets) { //----------------------------------- // Merge styles with parent styles, //----------------------------------- var merged = {}; styleSets.unshift(params.styles); - styleSets.forEach(function(styleSet) { - styleSet.children.forEach(function(style) { + styleSets.forEach(function (styleSet) { + styleSet.children.forEach(function (style) { merged[style.tagName] = merged[style.tagName] || {}; - style.children.forEach(function(styleEle) { + style.children.forEach(function (styleEle) { merged[style.tagName][styleEle.tagName] = styleEle; }); }); @@ -122,9 +118,9 @@ KmlLoader.prototype.kmlTagProcess = function(params, callback) { params.styles = {}; var keys = Object.keys(merged); - params.styles.children = keys.map(function(tagName) { + params.styles.children = keys.map(function (tagName) { var properties = Object.keys(merged[tagName]); - var children = properties.map(function(propName) { + var children = properties.map(function (propName) { return merged[tagName][propName]; }); return { @@ -146,26 +142,27 @@ KmlLoader.prototype.kmlTagProcess = function(params, callback) { } }; -KmlLoader.prototype.getObjectById = function(requestId, targetProp, callback) { +KmlLoader.prototype.getObjectById = function (requestId, targetProp, callback) { var self = this; if (!requestId) { - return callback.call(self, {children: []}); + return callback.call(self, { + children: [] + }); } - var results = {}; - var i, result, child; - if (requestId.indexOf("http://") === 0 || - requestId.indexOf("https://") === 0 || - requestId.indexOf(".kml") !== -1) { - - if (requestId.indexOf("://") === -1) { - requestId = self.kmlUrl.replace(/\/[^\/]+$/, "/") + requestId; + var results, i, child; + if (requestId.indexOf('http://') === 0 || + requestId.indexOf('https://') === 0 || + requestId.indexOf('.kml') !== -1) { + + if (requestId.indexOf('://') === -1) { + requestId = self.kmlUrl.replace(/\/[^/]+$/, '/') + requestId; } //--------------------------- // Load additional kml file //--------------------------- - var requestUrl = requestId.replace(/\#.*$/, ""); - var requestIdentify = requestId.replace(/^.*?\#/, ""); + var requestUrl = requestId.replace(/#.*$/, ''); + var requestIdentify = requestId.replace(/^.*?#/, ''); if (requestUrl in self[targetProp]) { self[targetProp][requestUrl] = self[targetProp][requestUrl] || {}; @@ -174,7 +171,7 @@ KmlLoader.prototype.getObjectById = function(requestId, targetProp, callback) { }; for (i = 0; i < results.children.length; i++) { child = results.children[i]; - if (child.tagName === "pair" && child.key === "normal") { + if (child.tagName === 'pair' && child.key === 'normal') { return self.getObjectById.call(self, child.styleIDs[0], targetProp, callback); } } @@ -185,17 +182,23 @@ KmlLoader.prototype.getObjectById = function(requestId, targetProp, callback) { var loader = new KmlLoader(self.map, self.exec, { url: requestUrl }); - loader.parseKmlFile(function(camera, anotherKmlData) { + loader.parseKmlFile(function (camera, anotherKmlData) { var extendProps = [ - {src: "styles", dst: "kmlStyles"}, - {src: "schemas", dst: "kmlSchemas"} + { + src: 'styles', + dst: 'kmlStyles' + }, + { + src: 'schemas', + dst: 'kmlSchemas' + } ]; - extendProps.forEach(function(property) { - var properties = anotherKmlData.get("kmlData")[property.src]; + extendProps.forEach(function (property) { + var properties = anotherKmlData.get('kmlData')[property.src]; self[property.dst][requestUrl] = {}; var keys = Object.keys(properties); - keys.forEach(function(key) { + keys.forEach(function (key) { self[property.dst][requestUrl][key] = properties[key]; }); }); @@ -206,7 +209,7 @@ KmlLoader.prototype.getObjectById = function(requestId, targetProp, callback) { }; for (i = 0; i < results.children.length; i++) { child = results.children[i]; - if (child.tagName === "pair" && child.key === "normal") { + if (child.tagName === 'pair' && child.key === 'normal') { return self.getObjectById.call(self, child.styleIDs[0], targetProp, callback); } } @@ -215,20 +218,22 @@ KmlLoader.prototype.getObjectById = function(requestId, targetProp, callback) { return; } - requestId = requestId.replace("#", ""); + requestId = requestId.replace('#', ''); if (requestId in self[targetProp] === false) { - callback.call(self, {children: []}); + callback.call(self, { + children: [] + }); return; } results = self[targetProp][requestId]; - results.children.filter(function(style) { - if (style.tagName !== "pair") { + results.children.filter(function (style) { + if (style.tagName !== 'pair') { return true; } for (var j = 0; j < style.children.length; j++) { - if (style.children[j].tagName === "key" && - style.children[j].value === "highlight") { + if (style.children[j].tagName === 'key' && + style.children[j].value === 'highlight') { return false; } } @@ -237,7 +242,7 @@ KmlLoader.prototype.getObjectById = function(requestId, targetProp, callback) { var containPairTag = false; for (i = 0; i < results.children.length; i++) { - if (results.children[i].tagName === "pair") { + if (results.children[i].tagName === 'pair') { containPairTag = true; break; } @@ -248,9 +253,9 @@ KmlLoader.prototype.getObjectById = function(requestId, targetProp, callback) { } //--------------------------------------------------------- - // should contain 'tagName = "key", value="normal"' only + // should contain 'tagName = 'key', value='normal'' only //--------------------------------------------------------- - self.getObjectById.call(self, results.children[0].styleIDs[0], targetProp, function(resultSets) { + self.getObjectById.call(self, results.children[0].styleIDs[0], targetProp, function (resultSets) { if (resultSets.children) { results = resultSets; } else { @@ -261,170 +266,170 @@ KmlLoader.prototype.getObjectById = function(requestId, targetProp, callback) { }; -KmlLoader.prototype.getStyleById = function(requestId, callback) { - this.getObjectById.call(this, requestId, "kmlStyles", callback); +KmlLoader.prototype.getStyleById = function (requestId, callback) { + this.getObjectById.call(this, requestId, 'kmlStyles', callback); }; -KmlLoader.prototype.getSchemaById = function(requestId, callback) { - this.getObjectById.call(this, requestId, "kmlSchemas", callback); +KmlLoader.prototype.getSchemaById = function (requestId, callback) { + this.getObjectById.call(this, requestId, 'kmlSchemas', callback); }; -KmlLoader.prototype.parseKmlTag = function(params, callback) { +KmlLoader.prototype.parseKmlTag = function (params, callback) { var self = this; switch (params.child.tagName) { - case "kml": - case "folder": - case "placemark": - case "document": - case "multigeometry": - self.parseContainerTag.call(self, { - placeMark: params.child, - styles: params.styles, - attrHolder: JSON.parse(JSON.stringify(params.attrHolder)) - }, callback); - break; - - case "photooverlay": - case "point": - self.parsePointTag.call(self, { - child: params.child, - placeMark: params.placeMark, - styles: params.styles, - attrHolder: params.attrHolder - }, callback); - break; - case "polygon": - self.parsePolygonTag.call(self, { - child: params.child, - placeMark: params.placeMark, - styles: params.styles, - attrHolder: params.attrHolder - }, callback); - break; - case "linestring": - self.parseLineStringTag.call(self, { - child: params.child, - placeMark: params.placeMark, - styles: params.styles, - attrHolder: params.attrHolder - }, callback); - break; - - case "groundoverlay": - self.parseGroundOverlayTag.call(self, { - child: params.child, - placeMark: params.placeMark, - styles: params.styles, - attrHolder: params.attrHolder - }, callback); - break; - case "networklink": - self.parseNetworkLinkTag.call(self, { - child: params.child, - placeMark: params.placeMark, - styles: params.styles, - attrHolder: params.attrHolder - }, callback); - break; - - case "lookat": - self.parseLookAtTag.call(self, { - child: params.child, - }, callback); - break; + case 'kml': + case 'folder': + case 'placemark': + case 'document': + case 'multigeometry': + self.parseContainerTag.call(self, { + placeMark: params.child, + styles: params.styles, + attrHolder: JSON.parse(JSON.stringify(params.attrHolder)) + }, callback); + break; + + case 'photooverlay': + case 'point': + self.parsePointTag.call(self, { + child: params.child, + placeMark: params.placeMark, + styles: params.styles, + attrHolder: params.attrHolder + }, callback); + break; + case 'polygon': + self.parsePolygonTag.call(self, { + child: params.child, + placeMark: params.placeMark, + styles: params.styles, + attrHolder: params.attrHolder + }, callback); + break; + case 'linestring': + self.parseLineStringTag.call(self, { + child: params.child, + placeMark: params.placeMark, + styles: params.styles, + attrHolder: params.attrHolder + }, callback); + break; - case "extendeddata": - self.parseExtendedDataTag.call(self, { - child: params.child, - placeMark: params.placeMark, - styles: params.styles, - attrHolder: params.attrHolder - }, callback); - break; - default: - params.attrHolder[params.child.tagName] = params.child; - callback(); + case 'groundoverlay': + self.parseGroundOverlayTag.call(self, { + child: params.child, + placeMark: params.placeMark, + styles: params.styles, + attrHolder: params.attrHolder + }, callback); + break; + case 'networklink': + self.parseNetworkLinkTag.call(self, { + child: params.child, + placeMark: params.placeMark, + styles: params.styles, + attrHolder: params.attrHolder + }, callback); + break; + + case 'lookat': + self.parseLookAtTag.call(self, { + child: params.child, + }, callback); + break; + + case 'extendeddata': + self.parseExtendedDataTag.call(self, { + child: params.child, + placeMark: params.placeMark, + styles: params.styles, + attrHolder: params.attrHolder + }, callback); + break; + default: + params.attrHolder[params.child.tagName] = params.child; + callback(); } }; -KmlLoader.prototype.parseExtendedDataTag = function(params, callback) { +KmlLoader.prototype.parseExtendedDataTag = function (params, callback) { var self = this; if (params.child && params.child.children) { params.attrHolder.extendeddata = {}; - params.child.children.forEach(function(child) { - switch(child.tagName) { - case "data": - child.children.forEach(function(data) { - var dataName = child.name.toLowerCase(); - switch(data.tagName) { - case "displayname": - params.attrHolder.extendeddata[dataName + "/displayname"] = data.value; - break; - case "value": - params.attrHolder.extendeddata[dataName] = data.value; - break; - default: - break; + params.child.children.forEach(function (child) { + switch (child.tagName) { + case 'data': + child.children.forEach(function (data) { + var dataName = child.name.toLowerCase(); + switch (data.tagName) { + case 'displayname': + params.attrHolder.extendeddata[dataName + '/displayname'] = data.value; + break; + case 'value': + params.attrHolder.extendeddata[dataName] = data.value; + break; + default: + break; + } + }); + break; + case 'schemadata': + self.getSchemaById(child.schemaUrl, function (schemas) { + var schemaUrl = schemas.name; + schemas.children.forEach(function (simplefield) { + if (simplefield.tagName !== 'simplefield') { + return; } - }); - break; - case "schemadata": - self.getSchemaById(child.schemaUrl, function(schemas) { - var schemaUrl = schemas.name; - schemas.children.forEach(function(simplefield) { - if (simplefield.tagName !== "simplefield") { - return; - } - if ("children" in simplefield) { - simplefield.children.forEach(function(valueTag) { - var schemaPath = schemaUrl + "/" + simplefield.name + "/" + valueTag.tagName; - schemaPath = schemaPath.toLowerCase(); - params.attrHolder.extendeddata[schemaPath] = valueTag.value; - }); - } else { - var schemaPath = schemaUrl + "/" + simplefield.name; + if ('children' in simplefield) { + simplefield.children.forEach(function (valueTag) { + var schemaPath = schemaUrl + '/' + simplefield.name + '/' + valueTag.tagName; schemaPath = schemaPath.toLowerCase(); - params.attrHolder.extendeddata[schemaPath] = simplefield.value; - } - }); - child.children.forEach(function(simpledata) { - var schemaPath = schemaUrl + "/" + simpledata.name; + params.attrHolder.extendeddata[schemaPath] = valueTag.value; + }); + } else { + var schemaPath = schemaUrl + '/' + simplefield.name; schemaPath = schemaPath.toLowerCase(); - params.attrHolder.extendeddata[schemaPath] = simpledata.value; - }); + params.attrHolder.extendeddata[schemaPath] = simplefield.value; + } }); - break; + child.children.forEach(function (simpledata) { + var schemaPath = schemaUrl + '/' + simpledata.name; + schemaPath = schemaPath.toLowerCase(); + params.attrHolder.extendeddata[schemaPath] = simpledata.value; + }); + }); + break; - default: + default: - child.children.forEach(function(data) { - params.attrHolder.extendeddata[child.tagName] = child; - }); - break; + child.children.forEach(function (data) { + params.attrHolder.extendeddata[child.tagName] = data; + }); + break; } }); } callback(); }; -KmlLoader.prototype.parseContainerTag = function(params, callback) { +KmlLoader.prototype.parseContainerTag = function (params, callback) { var self = this; var keys = Object.keys(params.placeMark); - keys = keys.filter(function(key) { - return key !== "children"; + keys = keys.filter(function (key) { + return key !== 'children'; }); //-------------------------------------------------------- // Generate overlays or load another files...etc //-------------------------------------------------------- var children = new BaseArrayClass(params.placeMark.children); - children.mapAsync(function(child, cb) { + children.mapAsync(function (child, cb) { //------------------------- // Copy parent information //------------------------- - keys.forEach(function(key) { + keys.forEach(function (key) { if (key in child === false) { child[key] = params.placeMark[key]; } @@ -438,8 +443,8 @@ KmlLoader.prototype.parseContainerTag = function(params, callback) { styles: params.styles, attrHolder: params.attrHolder }, cb); - }, function(overlays) { - overlays = overlays.filter(function(overlay) { + }, function (overlays) { + overlays = overlays.filter(function (overlay) { return !!overlay; }); var attrNames = Object.keys(params.attrHolder); @@ -447,14 +452,14 @@ KmlLoader.prototype.parseContainerTag = function(params, callback) { overlays.push(new BaseClass()); } - if (params.placeMark.tagName === "placemark") { + if (params.placeMark.tagName === 'placemark') { // attrNames.forEach(function(name) { // switch(name) { - // case "extendeddata": + // case 'extendeddata': // overlays[0].set(name, params.attrHolder[name]); // break; - // case "snippet": - // overlays[0].set("_snippet", params.attrHolder[name].value); + // case 'snippet': + // overlays[0].set('_snippet', params.attrHolder[name].value); // break; // default: // overlays[0].set(name, params.attrHolder[name].value); @@ -465,18 +470,18 @@ KmlLoader.prototype.parseContainerTag = function(params, callback) { callback.call(self, overlays[0]); } else { var container = new BaseArrayClass(overlays); - Object.defineProperty(container, "tagName", { - value: params.placeMark.tagName, - writable: false + Object.defineProperty(container, 'tagName', { + value: params.placeMark.tagName, + writable: false }); - attrNames.forEach(function(name) { - switch(name) { - case "extendeddata": - container.set(name, params.attrHolder[name]); - break; - default: - container.set(name, params.attrHolder[name].value); - break; + attrNames.forEach(function (name) { + switch (name) { + case 'extendeddata': + container.set(name, params.attrHolder[name]); + break; + default: + container.set(name, params.attrHolder[name].value); + break; } }); callback.call(self, container); @@ -484,86 +489,86 @@ KmlLoader.prototype.parseContainerTag = function(params, callback) { }); }; -KmlLoader.prototype.parsePointTag = function(params, callback) { +KmlLoader.prototype.parsePointTag = function (params, callback) { var self = this; -//console.log("parsePointTag", params); + //console.log('parsePointTag', params); //-------------- // add a marker //-------------- var markerOptions = {}; - params.styles.children.forEach(function(child) { + params.styles.children.forEach(function (child) { switch (child.tagName) { - // // Don't use this code because this replace original 'description' field. - // case "balloonstyle": - // child.children.forEach(function(style) { - // switch (style.tagName) { - // case "description": - // markerOptions.description = { - // value: style.value - // }; - // break; - // } - // }); - // break; - - case "iconstyle": - child.children.forEach(function(style) { - switch (style.tagName) { - case "hotspot": - markerOptions.icon = markerOptions.icon || {}; - markerOptions.icon.hotspot = style; - break; - case "heading": - markerOptions.icon = markerOptions.icon || {}; - markerOptions.icon.rotation = style; - break; - case "icon": - markerOptions.icon = markerOptions.icon || {}; - markerOptions.icon.url = style.children[0].value; - break; - // case "color": - // markerOptions.icon = markerOptions.icon || {}; - // markerOptions.icon.color = kmlColorToRGBA(style.value); - // break; - } - }); - break; - default: + // // Don't use this code because this replace original 'description' field. + // case 'balloonstyle': + // child.children.forEach(function(style) { + // switch (style.tagName) { + // case 'description': + // markerOptions.description = { + // value: style.value + // }; + // break; + // } + // }); + // break; + + case 'iconstyle': + child.children.forEach(function (style) { + switch (style.tagName) { + case 'hotspot': + markerOptions.icon = markerOptions.icon || {}; + markerOptions.icon.hotspot = style; + break; + case 'heading': + markerOptions.icon = markerOptions.icon || {}; + markerOptions.icon.rotation = style; + break; + case 'icon': + markerOptions.icon = markerOptions.icon || {}; + markerOptions.icon.url = style.children[0].value; + break; + // case 'color': + // markerOptions.icon = markerOptions.icon || {}; + // markerOptions.icon.color = kmlColorToRGBA(style.value); + // break; + } + }); + break; + default: } }); if (params.child.children) { var options = new BaseClass(); - params.child.children.forEach(function(child) { + params.child.children.forEach(function (child) { options.set(child.tagName, child); }); - params.child.children.forEach(function(child) { + params.child.children.forEach(function (child) { switch (child.tagName) { - case "point": - var coordinates = findTag(child.children, "coordinates", "coordinates"); - if (coordinates) { - markerOptions.position = coordinates[0]; - } - break; - case "coordinates": - markerOptions.position = child.coordinates[0]; - break; - // case "description": + case 'point': + var coordinates = findTag(child.children, 'coordinates', 'coordinates'); + if (coordinates) { + markerOptions.position = coordinates[0]; + } + break; + case 'coordinates': + markerOptions.position = child.coordinates[0]; + break; + // case 'description': // if (markerOptions.description) { // markerOptions.description = templateRenderer(markerOptions.description, options); // } // markerOptions.description = templateRenderer(markerOptions.description, options); // break; - // case "snippet": + // case 'snippet': // if (markerOptions.snippet) { // markerOptions.snippet = templateRenderer(markerOptions.snippet, options); // } // markerOptions.snippet = templateRenderer(markerOptions.snippet, options); // break; - default: + default: } }); @@ -575,21 +580,21 @@ KmlLoader.prototype.parsePointTag = function(params, callback) { self.camera.target.push(markerOptions.position); - var ignoreProperties = ["coordinates", "styleIDs", "children"]; - (Object.keys(params.attrHolder)).forEach(function(pName) { + var ignoreProperties = ['coordinates', 'styleIDs', 'children']; + (Object.keys(params.attrHolder)).forEach(function (pName) { if (ignoreProperties.indexOf(pName) === -1 && pName in markerOptions === false) { markerOptions[pName] = params.attrHolder[pName]; } }); -//console.log(markerOptions); - (new Promise(function(resolve, reject) { + //console.log(markerOptions); + (new Promise(function (resolve, reject) { // if (markerOptions.icon && markerOptions.icon.color) { // var image = new Image(); // image.onload = function() { // - // var canvas = document.createElement("canvas"); + // var canvas = document.createElement('canvas'); // var ctx = canvas.getContext('2d'); // canvas.width = image.width; // canvas.height = image.height; @@ -601,15 +606,15 @@ KmlLoader.prototype.parsePointTag = function(params, callback) { // self.map.addMarker(markerOptions, resolve); // }; // image.onerror = function(e) { - // //console.warn(e.message || "Can not load " + markerOptions.icon.url); + // //console.warn(e.message || 'Can not load ' + markerOptions.icon.url); // delete markerOptions.icon.color; // self.map.addMarker(markerOptions, resolve); // }; // // image.src = markerOptions.icon.url; // } else { - self.map.addMarker(markerOptions, resolve); -// } + self.map.addMarker(markerOptions).then(resolve).catch(reject); + // } })).then(callback); }; @@ -621,10 +626,10 @@ function findTag(children, tagName, fieldName) { } } } -KmlLoader.prototype.parsePolygonTag = function(params, callback) { +KmlLoader.prototype.parsePolygonTag = function (params, callback) { var self = this; -// console.log('polygonPlacemark', params); + // console.log('polygonPlacemark', params); //-------------- // add a polygon //-------------- @@ -635,71 +640,69 @@ KmlLoader.prototype.parsePolygonTag = function(params, callback) { strokeWidth: 1, clickable: true }; - params.child.children.forEach(function(element) { + params.child.children.forEach(function (element) { var coordinates; switch (element.tagName) { - case "outerboundaryis": - if (element.children.length === 1) { - switch(element.children[0].tagName) { - case "linearring": - coordinates = element.children[0].children[0].coordinates; - break; - case "coordinates": - coordinates = findTag(element.children, "coordinates", "coordinates"); - break; - } - coordinates.forEach(function(latLng) { - self.camera.target.push(latLng); - }); - polygonOptions.points = coordinates; + case 'outerboundaryis': + if (element.children.length === 1) { + switch (element.children[0].tagName) { + case 'linearring': + coordinates = element.children[0].children[0].coordinates; + break; + case 'coordinates': + coordinates = findTag(element.children, 'coordinates', 'coordinates'); + break; } + coordinates.forEach(function (latLng) { + self.camera.target.push(latLng); + }); + polygonOptions.points = coordinates; + } + break; + case 'innerboundaryis': + switch (element.children[0].tagName) { + case 'linearring': + coordinates = element.children[0].children[0].coordinates; break; - case "innerboundaryis": - switch(element.children[0].tagName) { - case "linearring": - coordinates = element.children[0].children[0].coordinates; - break; - case "coordinates": - coordinates = element.children[0].coordinates; - break; - } - polygonOptions.holes.push(coordinates); + case 'coordinates': + coordinates = element.children[0].coordinates; break; + } + polygonOptions.holes.push(coordinates); + break; } }); - params.styles.children.forEach(function(style) { - var keys; + params.styles.children.forEach(function (style) { switch (style.tagName) { - case "polystyle": - style.children.forEach(function(node) { - switch(node.tagName) { - case "color": - polygonOptions.fillColor = kmlColorToRGBA(node.value); - break; - case "fill": - polygonOptions.fill = node.value === "1"; - break; - case "outline": - polygonOptions.outline = node.value === "1"; - break; - } - }); - break; - + case 'polystyle': + style.children.forEach(function (node) { + switch (node.tagName) { + case 'color': + polygonOptions.fillColor = kmlColorToRGBA(node.value); + break; + case 'fill': + polygonOptions.fill = node.value === '1'; + break; + case 'outline': + polygonOptions.outline = node.value === '1'; + break; + } + }); + break; - case "linestyle": - style.children.forEach(function(node) { - switch(node.tagName) { - case "color": - polygonOptions.strokeColor = kmlColorToRGBA(node.value); - break; - case "width": - polygonOptions.strokeWidth = parseFloat(node.value); - break; - } - }); - break; + case 'linestyle': + style.children.forEach(function (node) { + switch (node.tagName) { + case 'color': + polygonOptions.strokeColor = kmlColorToRGBA(node.value); + break; + case 'width': + polygonOptions.strokeWidth = parseFloat(node.value); + break; + } + }); + break; } }); @@ -715,21 +718,20 @@ KmlLoader.prototype.parsePolygonTag = function(params, callback) { polygonOptions.strokeColor = polygonOptions.strokeColor || [255, 255, 255, 255]; } - - var ignoreProperties = ["coordinates", "styleIDs", "children"]; - (Object.keys(params.attrHolder)).forEach(function(pName) { + var ignoreProperties = ['coordinates', 'styleIDs', 'children']; + (Object.keys(params.attrHolder)).forEach(function (pName) { if (ignoreProperties.indexOf(pName) === -1 && pName in polygonOptions === false) { polygonOptions[pName] = params.attrHolder[pName]; } }); -// console.log('polygonOptions', polygonOptions); + // console.log('polygonOptions', polygonOptions); self.map.addPolygon(polygonOptions, callback); }; -KmlLoader.prototype.parseLineStringTag = function(params, callback) { +KmlLoader.prototype.parseLineStringTag = function (params, callback) { //console.log(JSON.parse(JSON.stringify(params))); var self = this; //-------------- @@ -740,9 +742,9 @@ KmlLoader.prototype.parseLineStringTag = function(params, callback) { clickable: true }; if (params.child.children) { - params.child.children.forEach(function(child) { - if (child.tagName === "coordinates") { - child.coordinates.forEach(function(latLng) { + params.child.children.forEach(function (child) { + if (child.tagName === 'coordinates') { + child.coordinates.forEach(function (latLng) { self.camera.target.push(latLng); polylineOptions.points.push(latLng); }); @@ -750,44 +752,43 @@ KmlLoader.prototype.parseLineStringTag = function(params, callback) { }); } - params.styles.children.forEach(function(style) { + params.styles.children.forEach(function (style) { switch (style.tagName) { - case "linestyle": - case "polystyle": - style.children.forEach(function(node) { - switch(node.tagName) { - case "color": - polylineOptions.color = kmlColorToRGBA(node.value); - break; - case "width": - polylineOptions.width = parseFloat(node.value); - break; - } - }); - break; - default: + case 'linestyle': + case 'polystyle': + style.children.forEach(function (node) { + switch (node.tagName) { + case 'color': + polylineOptions.color = kmlColorToRGBA(node.value); + break; + case 'width': + polylineOptions.width = parseFloat(node.value); + break; + } + }); + break; + default: } }); - var ignoreProperties = ["coordinates", "styleIDs", "children"]; - (Object.keys(params.attrHolder)).forEach(function(pName) { + var ignoreProperties = ['coordinates', 'styleIDs', 'children']; + (Object.keys(params.attrHolder)).forEach(function (pName) { if (ignoreProperties.indexOf(pName) === -1 && pName in polylineOptions === false) { polylineOptions[pName] = params.attrHolder[pName]; } }); - //console.log('polylinePlacemark', polylineOptions); self.map.addPolyline(polylineOptions, callback); }; -KmlLoader.prototype.parseGroundOverlayTag = function(params, callback) { +KmlLoader.prototype.parseGroundOverlayTag = function (params, callback) { var self = this; -// console.log('parseGroundOverlayTag', params); + // console.log('parseGroundOverlayTag', params); //-------------- // add a ground overlay @@ -798,53 +799,59 @@ KmlLoader.prototype.parseGroundOverlayTag = function(params, callback) { clickable: true }; - params.child.children.forEach(function(child) { + params.child.children.forEach(function (child) { switch (child.tagName) { - case "color": - groundoveralyOptions.opacity = ((kmlColorToRGBA(child.value)).pop() / 256); - break; - case "icon": - child.children.forEach(function(iconAttrNode) { - switch (iconAttrNode.tagName) { - case "href": - groundoveralyOptions.url = iconAttrNode.value; - if (groundoveralyOptions.url && groundoveralyOptions.url.indexOf("://") === -1) { - var requestUrl = self.kmlUrl.replace(/\?.*$/, ""); - requestUrl = requestUrl.replace(/\#.*$/, ""); - requestUrl = requestUrl.replace(/[^\/]*$/, ""); - groundoveralyOptions.url = requestUrl + groundoveralyOptions.url; - } - break; + case 'color': + groundoveralyOptions.opacity = ((kmlColorToRGBA(child.value)).pop() / 256); + break; + case 'icon': + child.children.forEach(function (iconAttrNode) { + switch (iconAttrNode.tagName) { + case 'href': + groundoveralyOptions.url = iconAttrNode.value; + if (groundoveralyOptions.url && groundoveralyOptions.url.indexOf('://') === -1) { + var requestUrl = self.kmlUrl.replace(/\?.*$/, ''); + requestUrl = requestUrl.replace(/#.*$/, ''); + requestUrl = requestUrl.replace(/[^/]*$/, ''); + groundoveralyOptions.url = requestUrl + groundoveralyOptions.url; } - }); - break; - case "latlonbox": - var box = {}; - child.children.forEach(function(latlonboxAttrNode) { - box[latlonboxAttrNode.tagName] = parseFloat(latlonboxAttrNode.value); - }); - if (box.rotation) { - groundoveralyOptions.bearing = box.rotation; + break; } - var ne = {lat: box.north, lng: box.east}; - var sw = {lat: box.south, lng: box.west}; - groundoveralyOptions.bounds.push(ne); - groundoveralyOptions.bounds.push(sw); - self.camera.target.push(ne); - self.camera.target.push(sw); - break; - // case "gx:latlonquad": + }); + break; + case 'latlonbox': + var box = {}; + child.children.forEach(function (latlonboxAttrNode) { + box[latlonboxAttrNode.tagName] = parseFloat(latlonboxAttrNode.value); + }); + if (box.rotation) { + groundoveralyOptions.bearing = box.rotation; + } + var ne = { + lat: box.north, + lng: box.east + }; + var sw = { + lat: box.south, + lng: box.west + }; + groundoveralyOptions.bounds.push(ne); + groundoveralyOptions.bounds.push(sw); + self.camera.target.push(ne); + self.camera.target.push(sw); + break; + // case 'gx:latlonquad': // groundoveralyOptions.bounds = child.children[0].coordinates; // Array.prototype.push.apply(self.camera.target, child.children[0].coordinates); // break; - default: + default: } }); //delete params.child.children; -// console.log("groundoveralyOptions", groundoveralyOptions); + // console.log('groundoveralyOptions', groundoveralyOptions); - var ignoreProperties = ["coordinates", "styleIDs", "children"]; - (Object.keys(params.attrHolder)).forEach(function(pName) { + var ignoreProperties = ['coordinates', 'styleIDs', 'children']; + (Object.keys(params.attrHolder)).forEach(function (pName) { if (ignoreProperties.indexOf(pName) === -1 && pName in groundoveralyOptions === false) { groundoveralyOptions[pName] = params.attrHolder[pName]; @@ -854,84 +861,108 @@ KmlLoader.prototype.parseGroundOverlayTag = function(params, callback) { self.map.addGroundOverlay(groundoveralyOptions, callback); }; -KmlLoader.prototype.parseNetworkLinkTag = function(params, callback) { +KmlLoader.prototype.parseNetworkLinkTag = function (params, callback) { var self = this; var networkLinkOptions = {}; //console.log('parseNetworkLinkTag', params); var attrNames = Object.keys(params.attrHolder); - attrNames.forEach(function(attrName) { - switch(attrName.toLowerCase()) { - case "region": - networkLinkOptions.region = networkLinkOptions.region || {}; - params.attrHolder[attrName].children.forEach(function(gChild) { - switch(gChild.tagName) { - case "latlonaltbox": - var box = {}; - gChild.children.forEach(function(latlonboxAttrNode) { - box[latlonboxAttrNode.tagName] = parseFloat(latlonboxAttrNode.value); - }); - networkLinkOptions.region.bounds = { - se: {lat: box.south, lng: box.east}, - sw: {lat: box.south, lng: box.west}, - ne: {lat: box.north, lng: box.east}, - nw: {lat: box.north, lng: box.west} - }; - break; - case "lod": - networkLinkOptions.region.lod = networkLinkOptions.region.lod || {}; - networkLinkOptions.region.lod.minlodpixels = networkLinkOptions.region.lod.minlodpixels || -1; - networkLinkOptions.region.lod.maxlodpixels = networkLinkOptions.region.lod.maxlodpixels || -1; - gChild.children.forEach(function(lodEle) { - networkLinkOptions.region.lod[lodEle.tagName] = parseInt(lodEle.value); - }); - break; - } - }); - break; + attrNames.forEach(function (attrName) { + switch (attrName.toLowerCase()) { + case 'region': + networkLinkOptions.region = networkLinkOptions.region || {}; + params.attrHolder[attrName].children.forEach(function (gChild) { + switch (gChild.tagName) { + case 'latlonaltbox': + var box = {}; + gChild.children.forEach(function (latlonboxAttrNode) { + box[latlonboxAttrNode.tagName] = parseFloat(latlonboxAttrNode.value); + }); + networkLinkOptions.region.bounds = { + se: { + lat: box.south, + lng: box.east + }, + sw: { + lat: box.south, + lng: box.west + }, + ne: { + lat: box.north, + lng: box.east + }, + nw: { + lat: box.north, + lng: box.west + } + }; + break; + case 'lod': + networkLinkOptions.region.lod = networkLinkOptions.region.lod || {}; + networkLinkOptions.region.lod.minlodpixels = networkLinkOptions.region.lod.minlodpixels || -1; + networkLinkOptions.region.lod.maxlodpixels = networkLinkOptions.region.lod.maxlodpixels || -1; + gChild.children.forEach(function (lodEle) { + networkLinkOptions.region.lod[lodEle.tagName] = parseInt(lodEle.value); + }); + break; + } + }); + break; - default: - networkLinkOptions[attrName] = params.attrHolder[attrName]; + default: + networkLinkOptions[attrName] = params.attrHolder[attrName]; } }); - params.child.children.forEach(function(child) { - switch(child.tagName) { - case "visibility": - networkLinkOptions.visibility = child.value === "1"; - break; - case "link": - networkLinkOptions.link = networkLinkOptions.link || {}; - child.children.forEach(function(gChild) { - networkLinkOptions.link[gChild.tagName] = gChild.value; - }); - break; - case "region": - networkLinkOptions.region = networkLinkOptions.region || {}; - child.children.forEach(function(gChild) { - switch(gChild.tagName) { - case "latlonaltbox": - var box = {}; - gChild.children.forEach(function(latlonboxAttrNode) { - box[latlonboxAttrNode.tagName] = parseFloat(latlonboxAttrNode.value); - }); - networkLinkOptions.region.bounds = { - se: {lat: box.south, lng: box.east}, - sw: {lat: box.south, lng: box.west}, - ne: {lat: box.north, lng: box.east}, - nw: {lat: box.north, lng: box.west} - }; - break; - case "lod": - networkLinkOptions.region.lod = networkLinkOptions.region.lod || {}; - networkLinkOptions.region.lod.minlodpixels = networkLinkOptions.region.lod.minlodpixels || -1; - networkLinkOptions.region.lod.maxlodpixels = networkLinkOptions.region.lod.maxlodpixels || -1; - gChild.children.forEach(function(lodEle) { - networkLinkOptions.region.lod[lodEle.tagName] = parseInt(lodEle.value); - }); - break; - } - }); + params.child.children.forEach(function (child) { + switch (child.tagName) { + case 'visibility': + networkLinkOptions.visibility = child.value === '1'; + break; + case 'link': + networkLinkOptions.link = networkLinkOptions.link || {}; + child.children.forEach(function (gChild) { + networkLinkOptions.link[gChild.tagName] = gChild.value; + }); + break; + case 'region': + networkLinkOptions.region = networkLinkOptions.region || {}; + child.children.forEach(function (gChild) { + switch (gChild.tagName) { + case 'latlonaltbox': + var box = {}; + gChild.children.forEach(function (latlonboxAttrNode) { + box[latlonboxAttrNode.tagName] = parseFloat(latlonboxAttrNode.value); + }); + networkLinkOptions.region.bounds = { + se: { + lat: box.south, + lng: box.east + }, + sw: { + lat: box.south, + lng: box.west + }, + ne: { + lat: box.north, + lng: box.east + }, + nw: { + lat: box.north, + lng: box.west + } + }; + break; + case 'lod': + networkLinkOptions.region.lod = networkLinkOptions.region.lod || {}; + networkLinkOptions.region.lod.minlodpixels = networkLinkOptions.region.lod.minlodpixels || -1; + networkLinkOptions.region.lod.maxlodpixels = networkLinkOptions.region.lod.maxlodpixels || -1; + gChild.children.forEach(function (lodEle) { + networkLinkOptions.region.lod[lodEle.tagName] = parseInt(lodEle.value); + }); + break; + } + }); } }); @@ -941,22 +972,21 @@ KmlLoader.prototype.parseNetworkLinkTag = function(params, callback) { if (!networkLinkOptions.link) { // tag must contain tag. // If not contained, simply ignore the tag. - return callback.call(self, child); + return callback.call(self); } - - if (networkLinkOptions.link.href.indexOf("://") === -1 && networkLinkOptions.link.href.substr(0, 1) !== "/") { - var a = document.createElement("a"); + if (networkLinkOptions.link.href.indexOf('://') === -1 && networkLinkOptions.link.href.substr(0, 1) !== '/') { + var a = document.createElement('a'); a.href = self.kmlUrl; - networkLinkOptions.link.href = a.protocol + "//" + a.host + ":" + a.port + a.pathname.replace(/\/[^\/]+$/, "") + "/" + networkLinkOptions.link.href; + networkLinkOptions.link.href = a.protocol + '//' + a.host + ':' + a.port + a.pathname.replace(/\/[^/]+$/, '') + '/' + networkLinkOptions.link.href; a = null; } var networkOverlay = new BaseClass(); - networkOverlay.set("_loaded", false); - networkOverlay.set("_visible", false); - networkOverlay.on("_visible_changed", function(oldValue, newValue) { - var overlay = networkOverlay.get("overlay"); + networkOverlay.set('_loaded', false); + networkOverlay.set('_visible', false); + networkOverlay.on('_visible_changed', function (oldValue, newValue) { + var overlay = networkOverlay.get('overlay'); if (newValue === true) { if (overlay) { overlay.setVisible(true); @@ -965,8 +995,8 @@ KmlLoader.prototype.parseNetworkLinkTag = function(params, callback) { url: networkLinkOptions.link.href, clickable: self.options.clickable, suppressInfoWindows: self.options.suppressInfoWindows - }, function(overlay) { - networkOverlay.set("overlay", overlay); + }, function (overlay) { + networkOverlay.set('overlay', overlay); }); } } else { @@ -995,47 +1025,47 @@ KmlLoader.prototype.parseNetworkLinkTag = function(params, callback) { // 'fillColor' : '#00000000' // }, function(groundoverlay) { - if (networkLinkOptions.region && networkLinkOptions.link.viewrefreshmode === "onRegion") { - self.map.on(event.CAMERA_MOVE_END, function() { + if (networkLinkOptions.region && networkLinkOptions.link.viewrefreshmode === 'onRegion') { + self.map.on(event.CAMERA_MOVE_END, function () { var vRegion = self.map.getVisibleRegion(); var nRegion = new VisibleRegion(networkLinkOptions.region.bounds.sw, networkLinkOptions.region.bounds.ne); if (vRegion.contains(networkLinkOptions.region.bounds.sw) || - vRegion.contains(networkLinkOptions.region.bounds.se) || - vRegion.contains(networkLinkOptions.region.bounds.nw) || - vRegion.contains(networkLinkOptions.region.bounds.ne) || - nRegion.contains(vRegion.farLeft) || - nRegion.contains(vRegion.farRight) || - nRegion.contains(vRegion.nearLeft) || - nRegion.contains(vRegion.nearRight)) { + vRegion.contains(networkLinkOptions.region.bounds.se) || + vRegion.contains(networkLinkOptions.region.bounds.nw) || + vRegion.contains(networkLinkOptions.region.bounds.ne) || + nRegion.contains(vRegion.farLeft) || + nRegion.contains(vRegion.farRight) || + nRegion.contains(vRegion.nearLeft) || + nRegion.contains(vRegion.nearRight)) { (new BaseArrayClass([ networkLinkOptions.region.bounds.sw, networkLinkOptions.region.bounds.ne - ]).mapAsync(function(latLng, next) { + ]).mapAsync(function (latLng, next) { self.map.fromLatLngToPoint(latLng, next); - }, function(points) { + }, function (points) { var width = Math.abs(points[0][0] - points[1][0]); var height = Math.abs(points[0][1] - points[1][1]); var maxCondition = (networkLinkOptions.region.lod.maxlodpixels === -1 || - width <= networkLinkOptions.region.lod.maxlodpixels && - height <= networkLinkOptions.region.lod.maxlodpixels); + width <= networkLinkOptions.region.lod.maxlodpixels && + height <= networkLinkOptions.region.lod.maxlodpixels); var minCondition = (networkLinkOptions.region.lod.minlodpixels === -1 || - width >= networkLinkOptions.region.lod.minlodpixels && - height >= networkLinkOptions.region.lod.minlodpixels); + width >= networkLinkOptions.region.lod.minlodpixels && + height >= networkLinkOptions.region.lod.minlodpixels); if (maxCondition && minCondition) { // groundoverlay.setVisible(true); - networkOverlay.set("_visible", true); + networkOverlay.set('_visible', true); } else { // groundoverlay.setVisible(false); - networkOverlay.set("_visible", false); + networkOverlay.set('_visible', false); } })); } else { // groundoverlay.setVisible(false); - networkOverlay.set("_visible", false); + networkOverlay.set('_visible', false); } }); } else { @@ -1043,7 +1073,7 @@ KmlLoader.prototype.parseNetworkLinkTag = function(params, callback) { // Simply load another kml file //------------------------------- // groundoverlay.setVisible(true); - networkOverlay.set("_visible", networkLinkOptions.visibility); + networkOverlay.set('_visible', networkLinkOptions.visibility); } callback.call(networkOverlay); @@ -1051,32 +1081,31 @@ KmlLoader.prototype.parseNetworkLinkTag = function(params, callback) { }; -KmlLoader.prototype.parseLookAtTag = function(params, callback) { +KmlLoader.prototype.parseLookAtTag = function (params, callback) { var self = this; - if ("latitude" in params.child && "longitude" in params.child) { + if ('latitude' in params.child && 'longitude' in params.child) { self.camera.target = { lat: parseFloat(params.child.latitude), lng: parseFloat(params.child.longitude) }; } - if ("heading" in params.child) { + if ('heading' in params.child) { self.camera.bearing = parseInt(params.child.heading); } - if ("tilt" in params.child) { + if ('tilt' in params.child) { self.camera.tilt = parseInt(params.child.tilt); } callback.call(self); }; - //------------------------------- // KML color (AABBGGRR) to RGBA //------------------------------- function kmlColorToRGBA(colorStr) { var rgba = []; - colorStr = colorStr.replace("#", ""); + colorStr = colorStr.replace('#', ''); for (var i = 6; i >= 0; i -= 2) { rgba.push(parseInt(colorStr.substring(i, i + 2), 16)); } @@ -1085,43 +1114,42 @@ function kmlColorToRGBA(colorStr) { //------------------------------- // KML color (AABBGGRR) to rgba(RR, GG, BB, AA) //------------------------------- -function kmlColorToCSS(colorStr) { - var rgba = []; - colorStr = colorStr.replace("#", ""); - for (var i = 6; i >= 0; i -= 2) { - rgba.push(parseInt(colorStr.substring(i, i + 2), 16)); - } - return "rgba(" + rgba.join(",") + ")"; -} +// function kmlColorToCSS(colorStr) { +// var rgba = []; +// colorStr = colorStr.replace('#', ''); +// for (var i = 6; i >= 0; i -= 2) { +// rgba.push(parseInt(colorStr.substring(i, i + 2), 16)); +// } +// return 'rgba(' + rgba.join(',') + ')'; +// } //------------------------------- // Template engine //------------------------------- -function templateRenderer(html, marker) { - if (!html) { - return html; - } - var extendedData = marker.get("extendeddata"); - - return html.replace(/\$[\{\[](.+?)[\}\]]/gi, function(match, name) { - var textProp = marker.get(name); - var text = ""; - if (textProp) { - text = textProp.value; - if (extendedData) { - text = text.replace(/\$[\{\[](.+?)[\}\]]/gi, function(match1, name1) { - var extProp = extendedData[name1.toLowerCase()]; - var extValue = "${" + name1 + "}"; - if (extProp) { - extValue = extProp.value; - } - return extValue; - }); - } - } - return text; - }); -} - +// function templateRenderer(html, marker) { +// if (!html) { +// return html; +// } +// var extendedData = marker.get('extendeddata'); +// +// return html.replace(/\$[{[](.+?)[}]]/gi, function (match, name) { +// var textProp = marker.get(name); +// var text = ''; +// if (textProp) { +// text = textProp.value; +// if (extendedData) { +// text = text.replace(/\$[{[](.+?)[}]]/gi, function (match1, name1) { +// var extProp = extendedData[name1.toLowerCase()]; +// var extValue = '${' + name1 + '}'; +// if (extProp) { +// extValue = extProp.value; +// } +// return extValue; +// }); +// } +// } +// return text; +// }); +// } module.exports = KmlLoader; diff --git a/www/KmlOverlay.js b/www/KmlOverlay.js index c49ee69ea..8315d5cdb 100644 --- a/www/KmlOverlay.js +++ b/www/KmlOverlay.js @@ -1,304 +1,299 @@ - -var argscheck = require('cordova/argscheck'), - utils = require('cordova/utils'), - common = require('./Common'), - BaseClass = require('./BaseClass'), - event = require('./event'), - BaseArrayClass = require('./BaseArrayClass'), - HtmlInfoWindow = require('./HtmlInfoWindow'); +var utils = require('cordova/utils'), + common = require('./Common'), + BaseClass = require('./BaseClass'), + event = require('./event'), + BaseArrayClass = require('./BaseArrayClass'), + HtmlInfoWindow = require('./HtmlInfoWindow'); var XElement = null; -window.addEventListener('WebComponentsReady', function(e) { +window.addEventListener('WebComponentsReady', function () { var XElementPrototype = Object.create(HTMLElement.prototype); XElement = document.registerElement('pgm-sandbox', { - prototype: XElementPrototype + prototype: XElementPrototype }); }); - /***************************************************************************** * KmlOverlay Class *****************************************************************************/ -var exec; -var KmlOverlay = function(map, kmlId, camera, kmlData, kmlOverlayOptions) { - BaseClass.apply(this); - - var self = this; - //self.set("visible", kmlOverlayOptions.visible === undefined ? true : kmlOverlayOptions.visible); - //self.set("zIndex", kmlOverlayOptions.zIndex || 0); - Object.defineProperty(self, "_isReady", { - value: true, - writable: false - }); - Object.defineProperty(self, "type", { - value: "KmlOverlay", - writable: false - }); - Object.defineProperty(self, "id", { - value: kmlId, - writable: false - }); - Object.defineProperty(self, "map", { - value: map, - writable: false - }); - Object.defineProperty(self, "camera", { - value: camera, - writable: false +var KmlOverlay = function (map, kmlId, camera, kmlData, kmlOverlayOptions) { + BaseClass.apply(this); + + var self = this; + //self.set('visible', kmlOverlayOptions.visible === undefined ? true : kmlOverlayOptions.visible); + //self.set('zIndex', kmlOverlayOptions.zIndex || 0); + Object.defineProperty(self, '_isReady', { + value: true, + writable: false + }); + Object.defineProperty(self, 'type', { + value: 'KmlOverlay', + writable: false + }); + Object.defineProperty(self, 'id', { + value: kmlId, + writable: false + }); + Object.defineProperty(self, 'map', { + value: map, + writable: false + }); + Object.defineProperty(self, 'camera', { + value: camera, + writable: false + }); + Object.defineProperty(self, 'kmlData', { + value: kmlData, + writable: false + }); + + function templateRenderer(html, marker) { + var extendedData = marker.get('extendeddata'); + + return html.replace(/\$[{[].+?[}]]/gi, function (match, name) { + var text = ''; + if (marker.get(name)) { + text = marker.get(name).value; + } + if (extendedData && text) { + text = text.replace(/\$[{[].+?[}]]/gi, function (match1, name1) { + return extendedData[name1.toLowerCase()] || ''; + }); + } + return text; }); - Object.defineProperty(self, "kmlData", { - value: kmlData, - writable: false + } + + function parseBalloonStyle(balloonStyle) { + var css = {}; + var hasBgColor = false; + var keys = Object.keys(balloonStyle); + keys.forEach(function (key) { + switch (key.toLowerCase()) { + case 'bgcolor': + hasBgColor = true; + ballon.setBackgroundColor(common.kmlColorToCSS(balloonStyle[key])); + break; + case 'textcolor': + css.color = common.kmlColorToCSS(balloonStyle[key]); + break; + } }); + if (!hasBgColor) { + ballon.setBackgroundColor('white'); + } + return css; + } - function templateRenderer(html, marker) { - var extendedData = marker.get("extendeddata"); + self.set('clickable', kmlOverlayOptions.clickable); - return html.replace(/\$[\{\[](.+?)[\}\]]/gi, function(match, name) { - var text = ""; - if (marker.get(name)) { - text = marker.get(name).value; - } - if (extendedData && text) { - text = text.replace(/\$[\{\[](.+?)[\}\]]/gi, function(match1, name1) { - return extendedData[name1.toLowerCase()] || ""; - }); - } - return text; - }); + var ballon = new HtmlInfoWindow(); + var onOverlayClick = function (position, overlay) { + if (!self.get('clickable')) { + return; } - function parseBalloonStyle(balloonStyle) { - var css = {}; - var hasBgColor = false; - var keys = Object.keys(balloonStyle); - keys.forEach(function(key) { - switch(key.toLowerCase()) { - case "bgcolor": - hasBgColor = true; - ballon.setBackgroundColor(common.kmlColorToCSS(balloonStyle[key])); - break; - case "textcolor": - css.color = common.kmlColorToCSS(balloonStyle[key]); - break; + self.trigger(event.KML_CLICK, overlay, position); + + if (kmlOverlayOptions.suppressInfoWindows) { + return; + } + + var description = overlay.get('description'); + if (!description && overlay.get('extendeddata')) { + var extendeddata = overlay.get('extendeddata'); + var keys = Object.keys(extendeddata); + var table = []; + keys.forEach(function (key) { + if (extendeddata[key] !== '' && extendeddata[key] !== null && extendeddata[key] !== undefined) { + table.push('' + key + '' + extendeddata[key] + ''); } }); - if (!hasBgColor) { - ballon.setBackgroundColor("white"); + if (table.length > 0) { + table.unshift(''); + table.push('
'); + description = { + value: table.join('') + }; + overlay.set('description', description); } - return css; } - self.set("clickable", kmlOverlayOptions.clickable); - - var ballon = new HtmlInfoWindow(); - var onOverlayClick = function(position, overlay) { - if (!self.get("clickable")) { - return; - } - self.trigger(event.KML_CLICK, overlay, position); - - if (kmlOverlayOptions.suppressInfoWindows) { - return; + var html = []; + var result; + var descriptionTxt = ''; + if (description && description.value) { + descriptionTxt = description.value; + } + if (description && (descriptionTxt.indexOf('') > -1 || descriptionTxt.indexOf('script') > -1)) { + var text = templateRenderer(descriptionTxt, overlay); + // create a sandbox + // if (text.indexOf(''; + // } + result = document.createElement('div'); + if (overlay.get('name') && overlay.get('name').value) { + var name = document.createElement('div'); + name.style.fontWeight = 500; + name.style.fontSize = 'medium'; + name.style.marginBottom = 0; + name.style.whiteSpace = 'pre'; + name.innerText = overlay.get('name').value || ''; + result.appendChild(name); } - - var description = overlay.get("description"); - if (!description && overlay.get("extendeddata")) { - var extendeddata = overlay.get("extendeddata"); - var keys = Object.keys(extendeddata); - var table = []; - keys.forEach(function(key) { - if (extendeddata[key] !== "" && extendeddata[key] !== null && extendeddata[key] !== undefined) { - table.push("" + key + "" + extendeddata[key] + ""); - } - }); - if (table.length > 0) { - table.unshift(""); - table.push("
"); - description = { - value: table.join("") - }; - overlay.set("description", description); - } + if (overlay.get('snippet') && overlay.get('snippet').value.length > 0) { + var snippet = document.createElement('div'); + snippet.style.fontWeight = 300; + snippet.style.fontSize = 'small'; + snippet.style.whiteSpace = 'normal'; + snippet.style.whiteSpace = 'pre'; + snippet.style.fontFamily = 'Roboto,Arial,sans-serif'; + snippet.innerText = overlay.get('snippet').value || ''; + result.appendChild(snippet); } + if (text && text.length > 0) { + if (XElement) { + var xElement = new XElement(); + xElement.innerHTML = text; + result.appendChild(xElement); + } else { + var iframe = document.createElement('iframe'); + iframe.sandbox = 'allow-scripts allow-same-origin'; + iframe.frameBorder = 'no'; + iframe.scrolling = 'yes'; + iframe.style.overflow = 'hidden'; + iframe.addEventListener('load', function () { + iframe.contentWindow.document.open(); + iframe.contentWindow.document.write(text); + iframe.contentWindow.document.close(); + }, { + once: true + }); + result.appendChild(iframe); - var html = []; - var result; - var descriptionTxt = ""; - if (description && description.value) { - descriptionTxt = description.value; - } - if (description && (descriptionTxt.indexOf("") > -1 || descriptionTxt.indexOf("script") > -1)) { - var text = templateRenderer(descriptionTxt, overlay); - // create a sandbox - // if (text.indexOf(""; - // } - result = document.createElement("div"); - if (overlay.get('name') && overlay.get('name').value ) { - var name = document.createElement("div"); - name.style.fontWeight = 500; - name.style.fontSize = "medium"; - name.style.marginBottom = 0; - name.style.whiteSpace = "pre"; - name.innerText = overlay.get('name').value || ""; - result.appendChild(name); - } - if (overlay.get('snippet') && overlay.get('snippet').value.length > 0) { - var snippet = document.createElement("div"); - snippet.style.fontWeight = 300; - snippet.style.fontSize = "small"; - snippet.style.whiteSpace = "normal"; - snippet.style.whiteSpace = "pre"; - snippet.style.fontFamily = "Roboto,Arial,sans-serif"; - snippet.innerText = overlay.get('snippet').value || ""; - result.appendChild(snippet); - } - - if (text && text.length > 0) { - if (XElement) { - var xElement = new XElement(); - xElement.innerHTML = text; - result.appendChild(xElement); - } else { - - var iframe = document.createElement('iframe'); - iframe.sandbox = "allow-scripts allow-same-origin"; - iframe.frameBorder = "no"; - iframe.scrolling = "yes"; - iframe.style.overflow = "hidden"; - iframe.addEventListener('load', function() { - iframe.contentWindow.document.open(); - iframe.contentWindow.document.write(text); - iframe.contentWindow.document.close(); - }, { - once: true - }); - result.appendChild(iframe); - - } } + } + } else { + if (overlay.get('description')) { + html.push('
${description}
'); } else { - if (overlay.get("description")) { - html.push("
${description}
"); - } else { - if (overlay.get("name")) { - html.push("
${name}
"); - } - if (overlay.get("_snippet")) { - html.push("
${_snippet}
"); - } + if (overlay.get('name')) { + html.push('
${name}
'); } - var prevMatchedCnt = 0; - result = html.join(""); - var matches = result.match(/\$[\{\[].+?[\}\]]/gi); - while(matches && matches.length !== prevMatchedCnt) { - prevMatchedCnt = matches.length; - result = templateRenderer(result, overlay); - matches = result.match(/\$[\{\[].+?[\}\]]/gi); + if (overlay.get('_snippet')) { + html.push('
${_snippet}
'); } } - var styles = null; - if (overlay.get("balloonstyle")) { - styles = parseBalloonStyle(overlay.get("balloonstyle")); + var prevMatchedCnt = 0; + result = html.join(''); + var matches = result.match(/\$[{[].+?[}]]/gi); + while (matches && matches.length !== prevMatchedCnt) { + prevMatchedCnt = matches.length; + result = templateRenderer(result, overlay); + matches = result.match(/\$[{[].+?[}]]/gi); } - styles = styles || {}; - styles.overflow = "scroll"; - styles["max-width"] = (map.getDiv().offsetWidth * 0.8) + "px"; - styles["max-height"] = (map.getDiv().offsetHeight * 0.6) + "px"; - - ballon.setContent(result, styles); - var marker = map.get("invisible_dot"); - if (overlay.type === "Marker") { - marker.setVisible(false); - ballon.open(overlay); - } else { - marker.setPosition(position); - marker.setVisible(true); - marker.off(event.MARKER_CLICK); - map.animateCamera({ - target: position, - duration: 300 - }, function() { - marker.setAnimation(plugin.google.maps.Animation.DROP, function() { - marker.on(event.MARKER_CLICK, function() { - ballon.open(marker); - }); - marker.trigger(event.MARKER_CLICK); + } + var styles = null; + if (overlay.get('balloonstyle')) { + styles = parseBalloonStyle(overlay.get('balloonstyle')); + } + styles = styles || {}; + styles.overflow = 'scroll'; + styles['max-width'] = (map.getDiv().offsetWidth * 0.8) + 'px'; + styles['max-height'] = (map.getDiv().offsetHeight * 0.6) + 'px'; + + ballon.setContent(result, styles); + var marker = map.get('invisible_dot'); + if (overlay.type === 'Marker') { + marker.setVisible(false); + ballon.open(overlay); + } else { + marker.setPosition(position); + marker.setVisible(true); + marker.off(event.MARKER_CLICK); + map.animateCamera({ + target: position, + duration: 300 + }, function () { + marker.setAnimation(window.plugin.google.maps.Animation.DROP, function () { + marker.on(event.MARKER_CLICK, function () { + ballon.open(marker); }); + marker.trigger(event.MARKER_CLICK); }); + }); - } - }; - - var eventNames = { - "Marker": event.MARKER_CLICK, - "Polyline": event.POLYLINE_CLICK, - "Polygon": event.POLYGON_CLICK, - "GroundOverlay": event.GROUND_OVERLAY_CLICK - }; - var seekOverlays = function(overlay) { - if (overlay instanceof BaseArrayClass) { - overlay.forEach(seekOverlays); - } else if (Array.isArray(overlay)) { - (new BaseArrayClass(overlay)).forEach(seekOverlays); - } else if (overlay instanceof BaseClass && overlay.type in eventNames) { - overlay.on(eventNames[overlay.type], onOverlayClick); - } - }; - - kmlData.forEach(seekOverlays); + } + }; -/* - var ignores = ["map", "id", "hashCode", "type"]; - for (var key in kmlOverlayOptions) { - if (ignores.indexOf(key) === -1) { - self.set(key, kmlOverlayOptions[key]); - } + var eventNames = { + 'Marker': event.MARKER_CLICK, + 'Polyline': event.POLYLINE_CLICK, + 'Polygon': event.POLYGON_CLICK, + 'GroundOverlay': event.GROUND_OVERLAY_CLICK + }; + var seekOverlays = function (overlay) { + if (overlay instanceof BaseArrayClass) { + overlay.forEach(seekOverlays); + } else if (Array.isArray(overlay)) { + (new BaseArrayClass(overlay)).forEach(seekOverlays); + } else if (overlay instanceof BaseClass && overlay.type in eventNames) { + overlay.on(eventNames[overlay.type], onOverlayClick); } -*/ + }; + + kmlData.forEach(seekOverlays); + + /* + var ignores = ['map', 'id', 'hashCode', 'type']; + for (var key in kmlOverlayOptions) { + if (ignores.indexOf(key) === -1) { + self.set(key, kmlOverlayOptions[key]); + } + } + */ }; utils.extend(KmlOverlay, BaseClass); -KmlOverlay.prototype.getPluginName = function() { - return this.map.getId() + "-kmloverlay"; +KmlOverlay.prototype.getPluginName = function () { + return this.map.getId() + '-kmloverlay'; }; -KmlOverlay.prototype.getHashCode = function() { - return this.hashCode; +KmlOverlay.prototype.getHashCode = function () { + return this.hashCode; }; -KmlOverlay.prototype.getDefaultViewport = function() { - return this.camera; +KmlOverlay.prototype.getDefaultViewport = function () { + return this.camera; }; -KmlOverlay.prototype.getKmlData = function() { - return this.kmlData; +KmlOverlay.prototype.getKmlData = function () { + return this.kmlData; }; -KmlOverlay.prototype.getMap = function() { - return this.map; +KmlOverlay.prototype.getMap = function () { + return this.map; }; -KmlOverlay.prototype.getId = function() { - return this.id; +KmlOverlay.prototype.getId = function () { + return this.id; }; -KmlOverlay.prototype.setClickable = function(clickable) { +KmlOverlay.prototype.setClickable = function (clickable) { clickable = common.parseBoolean(clickable); this.set('clickable', clickable); return this; }; -KmlOverlay.prototype.getClickable = function() { +KmlOverlay.prototype.getClickable = function () { return this.get('clickable'); }; -KmlOverlay.prototype.getVisible = function() { +KmlOverlay.prototype.getVisible = function () { return this.get('visible'); }; -KmlOverlay.prototype.setVisible = function(visible) { +KmlOverlay.prototype.setVisible = function (visible) { var self = this; if (self._isRemoved) { return; @@ -307,8 +302,8 @@ KmlOverlay.prototype.setVisible = function(visible) { visible = common.parseBoolean(visible); this.set('visible', visible); - var applyChildren = function(children) { - children.forEach(function(child) { + var applyChildren = function (children) { + children.forEach(function (child) { if ('setVisible' in child && typeof child.setVisible === 'function') { child.setVisible(visible); @@ -324,23 +319,22 @@ KmlOverlay.prototype.setVisible = function(visible) { applyChildren(self.kmlData); }; -KmlOverlay.prototype.remove = function(callback) { +KmlOverlay.prototype.remove = function (callback) { var self = this; if (self._isRemoved) { - if (typeof callback === "function") { + if (typeof callback === 'function') { return; } else { return Promise.resolve(); } } - Object.defineProperty(self, "_isRemoved", { - value: true, - writable: false + Object.defineProperty(self, '_isRemoved', { + value: true, + writable: false }); - - var removeChildren = function(children, cb) { - children.forEach(function(child, next) { + var removeChildren = function (children, cb) { + children.forEach(function (child, next) { if ('remove' in child && typeof child.remove === 'function') { child.remove(next); @@ -354,14 +348,14 @@ KmlOverlay.prototype.remove = function(callback) { }, cb); }; - var resolver = function(resolve, reject) { - removeChildren(self.kmlData, function() { + var resolver = function (resolve) { + removeChildren(self.kmlData, function () { self.destroy(); resolve.call(self); }); }; - if (typeof callback === "function") { + if (typeof callback === 'function') { resolver.call(self, callback, null); return; } else { @@ -369,5 +363,4 @@ KmlOverlay.prototype.remove = function(callback) { } }; - module.exports = KmlOverlay; diff --git a/www/LatLngBounds.js b/www/LatLngBounds.js index bb86e9a96..70f32f943 100644 --- a/www/LatLngBounds.js +++ b/www/LatLngBounds.js @@ -3,128 +3,128 @@ var LatLng = require('./LatLng'); /***************************************************************************** * LatLngBounds Class *****************************************************************************/ -var LatLngBounds = function() { - Object.defineProperty(this, "type", { - value: "LatLngBounds", - writable: false - }); - - var args = []; - if (arguments.length === 1 && - typeof arguments[0] === "object" && - "push" in arguments[0]) { - args = arguments[0]; - } else { - args = Array.prototype.slice.call(arguments, 0); - } - - for (var i = 0; i < args.length; i++) { - if (args[i] && "lat" in args[i] && "lng" in args[i]) { - this.extend(args[i]); - } +var LatLngBounds = function () { + Object.defineProperty(this, 'type', { + value: 'LatLngBounds', + writable: false + }); + + var args = []; + if (arguments.length === 1 && + typeof arguments[0] === 'object' && + 'push' in arguments[0]) { + args = arguments[0]; + } else { + args = Array.prototype.slice.call(arguments, 0); + } + + for (var i = 0; i < args.length; i++) { + if (args[i] && 'lat' in args[i] && 'lng' in args[i]) { + this.extend(args[i]); } + } }; LatLngBounds.prototype.northeast = null; LatLngBounds.prototype.southwest = null; -LatLngBounds.prototype.toString = function() { - return '{"southwest":' + this.southwest.toString() + ', "northeast":' + this.northeast.toString() + '}'; +LatLngBounds.prototype.toString = function () { + return '{"southwest":' + this.southwest.toString() + ', "northeast":' + this.northeast.toString() + '}'; }; -LatLngBounds.prototype.toUrlValue = function(precision) { - precision = precision || 6; - return "[" + this.southwest.toUrlValue(precision) + "," + this.northeast.toUrlValue(precision) + "]"; +LatLngBounds.prototype.toUrlValue = function (precision) { + precision = precision || 6; + return '[' + this.southwest.toUrlValue(precision) + ',' + this.northeast.toUrlValue(precision) + ']'; }; -LatLngBounds.prototype.extend = function(latLng, debug) { - if (latLng && "lat" in latLng && "lng" in latLng) { - if (!this.southwest && !this.northeast) { - this.southwest = latLng; - this.northeast = latLng; +LatLngBounds.prototype.extend = function (latLng) { + if (latLng && 'lat' in latLng && 'lng' in latLng) { + if (!this.southwest && !this.northeast) { + this.southwest = latLng; + this.northeast = latLng; + } else { + var south = Math.min(latLng.lat, this.southwest.lat); + var north = Math.max(latLng.lat, this.northeast.lat); + + var west = this.southwest.lng, + east = this.northeast.lng; + + if (west > 0 && east < 0) { + if (latLng.lng > 0) { + west = Math.min(latLng.lng, west); } else { - var south = Math.min(latLng.lat, this.southwest.lat); - var north = Math.max(latLng.lat, this.northeast.lat); - - var west = this.southwest.lng, - east = this.northeast.lng; - - if (west > 0 && east < 0) { - if (latLng.lng > 0) { - west = Math.min(latLng.lng, west); - } else { - east = Math.max(latLng.lng, east); - } - } else { - - west = Math.min(latLng.lng, this.southwest.lng); - east = Math.max(latLng.lng, this.northeast.lng); - } - - delete this.southwest; - delete this.northeast; - this.southwest = new LatLng(south, west); - this.northeast = new LatLng(north, east); + east = Math.max(latLng.lng, east); } + } else { + + west = Math.min(latLng.lng, this.southwest.lng); + east = Math.max(latLng.lng, this.northeast.lng); + } + + delete this.southwest; + delete this.northeast; + this.southwest = new LatLng(south, west); + this.northeast = new LatLng(north, east); } + } }; -LatLngBounds.prototype.getCenter = function() { - var centerLat = (this.southwest.lat + this.northeast.lat) / 2; +LatLngBounds.prototype.getCenter = function () { + var centerLat = (this.southwest.lat + this.northeast.lat) / 2; - var swLng = this.southwest.lng; - var neLng = this.northeast.lng; - var sumLng = swLng + neLng; - var centerLng = sumLng / 2; + var swLng = this.southwest.lng; + var neLng = this.northeast.lng; + var sumLng = swLng + neLng; + var centerLng = sumLng / 2; - if ((swLng > 0 && neLng < 0 && sumLng < 180)) { - centerLng += sumLng > 0 ? -180 : 180; - } - return new LatLng(centerLat, centerLng); + if ((swLng > 0 && neLng < 0 && sumLng < 180)) { + centerLng += sumLng > 0 ? -180 : 180; + } + return new LatLng(centerLat, centerLng); }; -LatLngBounds.prototype.contains = function(latLng) { - if (!latLng || !("lat" in latLng) || !("lng" in latLng)) { - return false; - } - var y = latLng.lat, - x = latLng.lng; - - var y90 = y + 90; - var south = this.southwest.lat, - north = this.northeast.lat, - west = this.southwest.lng, - east = this.northeast.lng; - var south90 = south + 90, - north90 = north + 90; - - var containX = false, - containY = false; - - if (west <= 0 && east <= 0 && west <= east) { - if (x > 0) { - containX = false; - } else { - containX = (west <= x && x <= east); - } - } else if (east <= 0 && west > 0 && east <= west) { - if (x > 0) { - containX = (x >= west && x <= 180); - } else { - containX = (-180 <= x && x <= west); - } - } else if (west <= 0 && east > 0 && west <= east) { - if (x < 0) { - containX = (west <= x && x <= 0); - } else { - containX = (x >= 0 && x <= east); - } +LatLngBounds.prototype.contains = function (latLng) { + if (!latLng || !('lat' in latLng) || !('lng' in latLng)) { + return false; + } + var y = latLng.lat, + x = latLng.lng; + + var y90 = y + 90; + var south = this.southwest.lat, + north = this.northeast.lat, + west = this.southwest.lng, + east = this.northeast.lng; + var south90 = south + 90, + north90 = north + 90; + + var containX = false, + containY = false; + + if (west <= 0 && east <= 0 && west <= east) { + if (x > 0) { + containX = false; } else { containX = (west <= x && x <= east); } + } else if (east <= 0 && west > 0 && east <= west) { + if (x > 0) { + containX = (x >= west && x <= 180); + } else { + containX = (-180 <= x && x <= west); + } + } else if (west <= 0 && east > 0 && west <= east) { + if (x < 0) { + containX = (west <= x && x <= 0); + } else { + containX = (x >= 0 && x <= east); + } + } else { + containX = (west <= x && x <= east); + } - containY = (south90 <= y90 && y90 <= north90) || //#a - (south >= 0 && north <= 0 && ((south <= y && y <= 90) || (y >= -90 && y<= north))); // #d + containY = (south90 <= y90 && y90 <= north90) || //#a + (south >= 0 && north <= 0 && ((south <= y && y <= 90) || (y >= -90 && y <= north))); // #d - return containX && containY; + return containX && containY; }; module.exports = LatLngBounds; diff --git a/www/Location.js b/www/Location.js index 299471885..49c47d0ed 100644 --- a/www/Location.js +++ b/www/Location.js @@ -1,17 +1,18 @@ /***************************************************************************** * Location Class *****************************************************************************/ +var LatLng = require('./LatLng'); var Location = function(params) { - var self = this; - self.latLng = params.latLng || new LatLng(params.lat || 0, params.lng || 0); - self.elapsedRealtimeNanos = params.elapsedRealtimeNanos; - self.time = params.time; - self.accuracy = params.accuracy || null; - self.bearing = params.bearing || null; - self.altitude = params.altitude || null; - self.speed = params.speed || null; - self.provider = params.provider; - self.hashCode = params.hashCode; + var self = this; + self.latLng = params.latLng || new LatLng(params.lat || 0, params.lng || 0); + self.elapsedRealtimeNanos = params.elapsedRealtimeNanos; + self.time = params.time; + self.accuracy = params.accuracy || null; + self.bearing = params.bearing || null; + self.altitude = params.altitude || null; + self.speed = params.speed || null; + self.provider = params.provider; + self.hashCode = params.hashCode; }; module.exports = Location; diff --git a/www/LocationService.js b/www/LocationService.js index 07392eaaf..ca38a56b0 100644 --- a/www/LocationService.js +++ b/www/LocationService.js @@ -1,4 +1,4 @@ - /***************************************************************************** +/***************************************************************************** * LocationService class *****************************************************************************/ var LatLng = require('./LatLng'); @@ -8,7 +8,7 @@ var LocationService = function(exec) { console.error(err); } return { - hasPermission: function(callback) { + hasPermission: function(callback, errorCallback) { var self = this; var resolver = function(resolve, reject) { @@ -22,28 +22,28 @@ var LocationService = function(exec) { }; var errorHandler = function(result) { - if (typeof error_callback === "function") { - error_callback.call(self, result); + if (typeof errorCallback === 'function') { + errorCallback.call(self, result); } else { (self.errorHandler || _errorHandler).call(self, result); } }; - if (typeof callback === "function") { + if (typeof callback === 'function') { resolver(callback, errorHandler); return self; } else { return new Promise(resolver); } }, - getMyLocation: function(params, success_callback, error_callback) { + getMyLocation: function(params, success_callback, errorCallback) { var self = this; - var args = [params || {}, success_callback || null, error_callback]; - if (typeof args[0] === "function") { - args.unshift({}); + var args = [params || {}, success_callback || null, errorCallback]; + if (typeof args[0] === 'function') { + args.unshift({}); } params = args[0]; success_callback = args[1]; - error_callback = args[2]; + errorCallback = args[2]; var resolver = function(resolve, reject) { @@ -59,14 +59,14 @@ var LocationService = function(exec) { params.enableHighAccuracy = params.enableHighAccuracy === true; var errorHandler = function(result) { - if (typeof error_callback === "function") { - error_callback.call(self, result); + if (typeof errorCallback === 'function') { + errorCallback.call(self, result); } else { (self.errorHandler || _errorHandler).call(self, result); } }; - if (typeof success_callback === "function") { + if (typeof success_callback === 'function') { resolver(success_callback, errorHandler); return self; } else { @@ -78,23 +78,23 @@ var LocationService = function(exec) { /** // TODO: -LocationService.prototype.followMyPosition = function(params, success_callback, error_callback) { +LocationService.prototype.followMyPosition = function(params, success_callback, errorCallback) { var self = this; - var args = [params || {}, success_callback || null, error_callback]; - if (typeof args[0] === "function") { + var args = [params || {}, success_callback || null, errorCallback]; + if (typeof args[0] === 'function') { args.unshift({}); } self.on('currentPosition_changed', success_callback); var successHandler = function(location) { location.latLng = new LatLng(location.latLng.lat, location.latLng.lng); - if (typeof success_callback === "function") { + if (typeof success_callback === 'function') { success_callback.call(self, location); } self.set('currentPosition', location); }; var errorHandler = function(result) { - if (typeof error_callback === "function") { - error_callback.call(self, result); + if (typeof errorCallback === 'function') { + errorCallback.call(self, result); } }; exec.call({ diff --git a/www/Map.js b/www/Map.js index 72a34eaea..919dd67cf 100644 --- a/www/Map.js +++ b/www/Map.js @@ -7,7 +7,6 @@ var utils = require('cordova/utils'), BaseClass = require('./BaseClass'), BaseArrayClass = require('./BaseArrayClass'), LatLng = require('./LatLng'), - LatLngBounds = require('./LatLngBounds'), MapTypeId = require('./MapTypeId'), event = require('./event'), VisibleRegion = require('./VisibleRegion'), @@ -19,7 +18,6 @@ var utils = require('cordova/utils'), GroundOverlay = require('./GroundOverlay'), KmlOverlay = require('./KmlOverlay'), KmlLoader = require('./KmlLoader'), - CameraPosition = require('./CameraPosition'), FusionTableOverlay = require('./FusionTableOverlay'), MarkerCluster = require('./MarkerCluster'); @@ -36,22 +34,22 @@ var Map = function(id, _exec) { delete self.map; - self.set("myLocation", false); - self.set("myLocationButton", false); + self.set('myLocation', false); + self.set('myLocationButton', false); self.MARKERS = {}; self.OVERLAYS = {}; - var infoWindowLayer = document.createElement("div"); - infoWindowLayer.style.position = "absolute"; + var infoWindowLayer = document.createElement('div'); + infoWindowLayer.style.position = 'absolute'; infoWindowLayer.style.left = 0; infoWindowLayer.style.top = 0; infoWindowLayer.style.width = 0; infoWindowLayer.style.height = 0; - infoWindowLayer.style.overflow = "visible"; - infoWindowLayer.style["z-index"] = 1; + infoWindowLayer.style.overflow = 'visible'; + infoWindowLayer.style['z-index'] = 1; - Object.defineProperty(self, "_layers", { + Object.defineProperty(self, '_layers', { value: { info: infoWindowLayer }, @@ -60,10 +58,10 @@ var Map = function(id, _exec) { }); self.on(event.MAP_CLICK, function() { - self.set("active_marker", undefined); + self.set('active_marker', undefined); }); - self.on("active_marker_changed", function(prevMarker, newMarker) { + self.on('active_marker_changed', function(prevMarker, newMarker) { var newMarkerId = newMarker ? newMarker.getId() : null; if (prevMarker) { prevMarker.hideInfoWindow.call(prevMarker); @@ -77,7 +75,7 @@ utils.extend(Map, Overlay); /** * @desc Recalculate the position of HTML elements */ -Map.prototype.refreshLayout = function(event) { +Map.prototype.refreshLayout = function() { this.exec.call(this, null, null, this.id, 'resizeMap', []); }; @@ -86,23 +84,23 @@ Map.prototype.getMap = function(meta, div, options) { args = [meta]; options = options || {}; - self.set("clickable", options.clickable === false ? false : true); - self.set("visible", options.visible === false ? false : true); + self.set('clickable', options.clickable === false ? false : true); + self.set('visible', options.visible === false ? false : true); if (options.controls) { - this.set("myLocation", options.controls.myLocation === true); - this.set("myLocationButton", options.controls.myLocationButton === true); + this.set('myLocation', options.controls.myLocation === true); + this.set('myLocationButton', options.controls.myLocationButton === true); } if (options.preferences && options.preferences.gestureBounds) { if (utils.isArray(options.preferences.gestureBounds) || - options.preferences.gestureBounds.type === "LatLngBounds") { + options.preferences.gestureBounds.type === 'LatLngBounds') { options.preferences.gestureBounds = common.convertToPositionArray(options.preferences.gestureBounds); } } if (!common.isDom(div)) { - self.set("visible", false); + self.set('visible', false); options = div; options = options || {}; if (options.camera) { @@ -127,10 +125,10 @@ Map.prototype.getMap = function(meta, div, options) { args.push(options); } else { - var positionCSS = common.getStyle(div, "position"); - if (!positionCSS || positionCSS === "static") { + var positionCSS = common.getStyle(div, 'position'); + if (!positionCSS || positionCSS === 'static') { // important for HtmlInfoWindow - div.style.position = "relative"; + div.style.position = 'relative'; } options = options || {}; if (options.camera) { @@ -157,8 +155,8 @@ Map.prototype.getMap = function(meta, div, options) { } args.push(options); - div.style.overflow = "hidden"; - self.set("div", div); + div.style.overflow = 'hidden'; + self.set('div', div); if (div.offsetWidth < 100 || div.offsetHeight < 100) { // If the map Div is too small, wait a little. @@ -168,14 +166,11 @@ Map.prototype.getMap = function(meta, div, options) { }, 250 + Math.random() * 100); return; } - var elements = []; - var elemId, clickable, size; - // Gets the map div size. // The plugin needs to consider the viewport zoom ratio // for the case window.innerHTML > body.offsetWidth. - elemId = common.getPluginDomId(div); + var elemId = common.getPluginDomId(div); args.push(elemId); } @@ -187,7 +182,7 @@ Map.prototype.getMap = function(meta, div, options) { //------------------------------------------------------------------------ // Clear background colors of map div parents after the map is created //------------------------------------------------------------------------ - var div = self.get("div"); + var div = self.get('div'); if (common.isDom(div)) { // Insert the infoWindow layer @@ -200,9 +195,9 @@ Map.prototype.getMap = function(meta, div, options) { } var positionCSS; for (var i = 0; i < div.children.length; i++) { - positionCSS = common.getStyle(div.children[i], "position"); - if (positionCSS === "static") { - div.children[i].style.position = "relative"; + positionCSS = common.getStyle(div.children[i], 'position'); + if (positionCSS === 'static') { + div.children[i].style.position = 'relative'; } } div.insertBefore(self._layers.info, div.firstChild); @@ -221,7 +216,7 @@ Map.prototype.getMap = function(meta, div, options) { div = div.parentNode; } } - cordova.fireDocumentEvent("plugin_touch", { + cordova.fireDocumentEvent('plugin_touch', { force: true }); @@ -255,16 +250,16 @@ Map.prototype.setOptions = function(options) { options = options || {}; if (options.controls) { - var myLocation = this.get("myLocation"); - if ("myLocation" in options.controls) { + var myLocation = this.get('myLocation'); + if ('myLocation' in options.controls) { myLocation = options.controls.myLocation === true; } - var myLocationButton = this.get("myLocationButton"); - if ("myLocationButton" in options.controls) { + var myLocationButton = this.get('myLocationButton'); + if ('myLocationButton' in options.controls) { myLocationButton = options.controls.myLocationButton === true; } - this.set("myLocation", myLocation); - this.set("myLocationButton", myLocationButton); + this.set('myLocation', myLocation); + this.set('myLocationButton', myLocationButton); options.controls.myLocation = myLocation; options.controls.myLocationButton = myLocationButton; } @@ -290,7 +285,7 @@ Map.prototype.setOptions = function(options) { if (options.preferences && options.preferences.gestureBounds) { if (utils.isArray(options.preferences.gestureBounds) || - options.preferences.gestureBounds.type === "LatLngBounds") { + options.preferences.gestureBounds.type === 'LatLngBounds') { options.preferences.gestureBounds = common.convertToPositionArray(options.preferences.gestureBounds); } } @@ -303,7 +298,7 @@ Map.prototype.setOptions = function(options) { }; Map.prototype.getMyLocation = function(params, success_callback, error_callback) { - return plugin.google.maps.LocationService.getMyLocation.call(this, params, success_callback, error_callback); + return window.plugin.google.maps.LocationService.getMyLocation.call(this, params, success_callback, error_callback); }; Map.prototype.setCameraTarget = function(latLng) { @@ -340,7 +335,7 @@ Map.prototype.clear = function(callback) { } // Close the active infoWindow - var active_marker = self.get("active_marker"); + var active_marker = self.get('active_marker'); if (active_marker) { active_marker.trigger(event.INFO_CLOSE); } @@ -352,7 +347,7 @@ Map.prototype.clear = function(callback) { id = ids[i]; instance = obj[id]; if (instance) { - if (typeof instance.remove === "function") { + if (typeof instance.remove === 'function') { instance.remove(); } instance.off(); @@ -364,7 +359,7 @@ Map.prototype.clear = function(callback) { clearObj(self.OVERLAYS); clearObj(self.MARKERS); - self.trigger("map_clear"); + self.trigger('map_clear'); var resolver = function(resolve, reject) { self.exec.call(self, @@ -375,7 +370,7 @@ Map.prototype.clear = function(callback) { }); }; - if (typeof callback === "function") { + if (typeof callback === 'function') { resolver(callback, self.errorHandler); } else { return new Promise(resolver); @@ -393,8 +388,8 @@ Map.prototype.clear = function(callback) { * MAP_TYPE_NONE */ Map.prototype.setMapTypeId = function(mapTypeId) { - if (mapTypeId !== MapTypeId[mapTypeId.replace("MAP_TYPE_", '')]) { - return this.errorHandler("Invalid MapTypeId was specified."); + if (mapTypeId !== MapTypeId[mapTypeId.replace('MAP_TYPE_', '')]) { + return this.errorHandler('Invalid MapTypeId was specified.'); } this.set('mapTypeId', mapTypeId); this.exec.call(this, null, this.errorHandler, this.id, 'setMapTypeId', [mapTypeId]); @@ -427,7 +422,7 @@ Map.prototype.setCameraBearing = function(bearing) { Map.prototype.moveCameraZoomIn = function(callback) { var self = this; - var cameraPosition = self.get("camera"); + var cameraPosition = self.get('camera'); cameraPosition.zoom++; cameraPosition.zoom = cameraPosition.zoom < 0 ? 0 : cameraPosition.zoom; @@ -436,7 +431,7 @@ Map.prototype.moveCameraZoomIn = function(callback) { }; Map.prototype.moveCameraZoomOut = function(callback) { var self = this; - var cameraPosition = self.get("camera"); + var cameraPosition = self.get('camera'); cameraPosition.zoom--; cameraPosition.zoom = cameraPosition.zoom < 0 ? 0 : cameraPosition.zoom; @@ -444,7 +439,7 @@ Map.prototype.moveCameraZoomOut = function(callback) { }; Map.prototype.animateCameraZoomIn = function(callback) { var self = this; - var cameraPosition = self.get("camera"); + var cameraPosition = self.get('camera'); cameraPosition.zoom++; cameraPosition.zoom = cameraPosition.zoom < 0 ? 0 : cameraPosition.zoom; cameraPosition.duration = 500; @@ -452,7 +447,7 @@ Map.prototype.animateCameraZoomIn = function(callback) { }; Map.prototype.animateCameraZoomOut = function(callback) { var self = this; - var cameraPosition = self.get("camera"); + var cameraPosition = self.get('camera'); cameraPosition.zoom--; cameraPosition.zoom = cameraPosition.zoom < 0 ? 0 : cameraPosition.zoom; cameraPosition.duration = 500; @@ -467,25 +462,25 @@ Map.prototype.animateCamera = function(cameraPosition, callback) { var self = this; var target = cameraPosition.target; - if (!target && "position" in cameraPosition) { + if (!target && 'position' in cameraPosition) { target = cameraPosition.position; } if (!target) { - return Promise.reject("No target field is specified."); + return Promise.reject('No target field is specified.'); } - // if (!("padding" in cameraPosition)) { + // if (!('padding' in cameraPosition)) { // cameraPosition.padding = 10; // } - if (utils.isArray(target) || target.type === "LatLngBounds") { + if (utils.isArray(target) || target.type === 'LatLngBounds') { target = common.convertToPositionArray(target); if (target.length === 0) { // skip if no point is specified - if (typeof callback === "function") { + if (typeof callback === 'function') { callback.call(self); return; } else { - return Promise.reject("No point is specified."); + return Promise.reject('No point is specified.'); } } } @@ -501,7 +496,7 @@ Map.prototype.animateCamera = function(cameraPosition, callback) { }); }; - if (typeof callback === "function") { + if (typeof callback === 'function') { resolver(callback, self.errorHandler); } else { return new Promise(resolver); @@ -515,25 +510,25 @@ Map.prototype.animateCamera = function(cameraPosition, callback) { Map.prototype.moveCamera = function(cameraPosition, callback) { var self = this; var target = cameraPosition.target; - if (!target && "position" in cameraPosition) { + if (!target && 'position' in cameraPosition) { target = cameraPosition.position; } if (!target) { - return Promise.reject("No target field is specified."); + return Promise.reject('No target field is specified.'); } - // if (!("padding" in cameraPosition)) { + // if (!('padding' in cameraPosition)) { // cameraPosition.padding = 10; // } - if (utils.isArray(target) || target.type === "LatLngBounds") { + if (utils.isArray(target) || target.type === 'LatLngBounds') { target = common.convertToPositionArray(target); if (target.length === 0) { // skip if no point is specified - if (typeof callback === "function") { + if (typeof callback === 'function') { callback.call(self); return; } else { - return Promise.reject("No point is specified."); + return Promise.reject('No point is specified.'); } } } @@ -549,7 +544,7 @@ Map.prototype.moveCamera = function(cameraPosition, callback) { }); }; - if (typeof callback === "function") { + if (typeof callback === 'function') { resolver(callback, self.errorHandler); } else { return new Promise(resolver); @@ -559,10 +554,10 @@ Map.prototype.moveCamera = function(cameraPosition, callback) { Map.prototype.setMyLocationButtonEnabled = function(enabled) { var self = this; enabled = common.parseBoolean(enabled); - this.set("myLocationButton", enabled); + this.set('myLocationButton', enabled); self.exec.call(self, null, this.errorHandler, this.id, 'setMyLocationEnabled', [{ myLocationButton: enabled, - myLocation: self.get("myLocation") === true + myLocation: self.get('myLocation') === true }], { sync: true }); @@ -572,9 +567,9 @@ Map.prototype.setMyLocationButtonEnabled = function(enabled) { Map.prototype.setMyLocationEnabled = function(enabled) { var self = this; enabled = common.parseBoolean(enabled); - this.set("myLocation", enabled); + this.set('myLocation', enabled); self.exec.call(self, null, this.errorHandler, this.id, 'setMyLocationEnabled', [{ - myLocationButton: self.get("myLocationButton") === true, + myLocationButton: self.get('myLocationButton') === true, myLocation: enabled }], { sync: true @@ -607,20 +602,20 @@ Map.prototype.getFocusedBuilding = function(callback) { self.id, 'getFocusedBuilding', []); }; - if (typeof callback === "function") { + if (typeof callback === 'function') { resolver(callback, self.errorHandler); } else { return new Promise(resolver); } }; Map.prototype.getVisible = function() { - return this.get("visible"); + return this.get('visible'); }; Map.prototype.setVisible = function(isVisible) { cordova.fireDocumentEvent('plugin_touch'); var self = this; isVisible = common.parseBoolean(isVisible); - self.set("visible", isVisible); + self.set('visible', isVisible); self.exec.call(self, null, self.errorHandler, this.id, 'setVisible', [isVisible]); return this; }; @@ -629,12 +624,12 @@ Map.prototype.setClickable = function(isClickable) { cordova.fireDocumentEvent('plugin_touch'); var self = this; isClickable = common.parseBoolean(isClickable); - self.set("clickable", isClickable); + self.set('clickable', isClickable); self.exec.call(self, null, self.errorHandler, this.id, 'setClickable', [isClickable]); return this; }; Map.prototype.getClickable = function() { - return this.get("clickable"); + return this.get('clickable'); }; @@ -653,7 +648,7 @@ Map.prototype.setAllGesturesEnabled = function(enabled) { * @return {CameraPosition} */ Map.prototype.getCameraPosition = function() { - return this.get("camera"); + return this.get('camera'); }; /** @@ -664,32 +659,32 @@ Map.prototype.remove = function(callback) { if (self._isRemoved) { return; } - Object.defineProperty(self, "_isRemoved", { + Object.defineProperty(self, '_isRemoved', { value: true, writable: false }); - self.trigger("remove"); -// var div = self.get('div'); -// if (div) { -// while (div) { -// if (div.style) { -// div.style.backgroundColor = ''; -// } -// if (div.classList) { -// div.classList.remove('_gmaps_cdv_'); -// } else if (div.className) { -// div.className = div.className.replace(/_gmaps_cdv_/g, ""); -// div.className = div.className.replace(/\s+/g, " "); -// } -// div = div.parentNode; -// } -// } -// self.set('div', undefined); + self.trigger('remove'); + // var div = self.get('div'); + // if (div) { + // while (div) { + // if (div.style) { + // div.style.backgroundColor = ''; + // } + // if (div.classList) { + // div.classList.remove('_gmaps_cdv_'); + // } else if (div.className) { + // div.className = div.className.replace(/_gmaps_cdv_/g, ''); + // div.className = div.className.replace(/\s+/g, ' '); + // } + // div = div.parentNode; + // } + // } + // self.set('div', undefined); // Close the active infoWindow - var active_marker = self.get("active_marker"); + var active_marker = self.get('active_marker'); if (active_marker) { active_marker.trigger(event.INFO_CLOSE); } @@ -701,7 +696,7 @@ Map.prototype.remove = function(callback) { id = ids[i]; instance = obj[id]; if (instance) { - if (typeof instance.remove === "function") { + if (typeof instance.remove === 'function') { instance.remove(); } instance.off(); @@ -726,7 +721,7 @@ Map.prototype.remove = function(callback) { }); }; - if (typeof callback === "function") { + if (typeof callback === 'function') { resolver(callback, self.errorHandler); } else { return new Promise(resolver); @@ -736,7 +731,7 @@ Map.prototype.remove = function(callback) { Map.prototype.toDataURL = function(params, callback) { var args = [params || {}, callback]; - if (typeof args[0] === "function") { + if (typeof args[0] === 'function') { args.unshift({}); } @@ -753,7 +748,7 @@ Map.prototype.toDataURL = function(params, callback) { self.id, 'toDataURL', [params]); }; - if (typeof callback === "function") { + if (typeof callback === 'function') { resolver(callback, self.errorHandler); } else { return new Promise(resolver); @@ -764,7 +759,7 @@ Map.prototype.toDataURL = function(params, callback) { * Show the map into the specified div. */ Map.prototype.getDiv = function() { - return this.get("div"); + return this.get('div'); }; /** @@ -775,13 +770,13 @@ Map.prototype.setDiv = function(div) { args = []; if (!common.isDom(div)) { - div = self.get("div"); + div = self.get('div'); if (common.isDom(div)) { - div.removeAttribute("__pluginMapId"); + div.removeAttribute('__pluginMapId'); } - self.set("div", null); + self.set('div', null); } else { - div.setAttribute("__pluginMapId", self.id); + div.setAttribute('__pluginMapId', self.id); // Insert the infoWindow layer if (self._layers.info.parentNode) { @@ -793,9 +788,9 @@ Map.prototype.setDiv = function(div) { } var positionCSS; for (var i = 0; i < div.children.length; i++) { - positionCSS = common.getStyle(div.children[i], "position"); - if (positionCSS === "static") { - div.children[i].style.position = "relative"; + positionCSS = common.getStyle(div.children[i], 'position'); + if (positionCSS === 'static') { + div.children[i].style.position = 'relative'; } } div.insertBefore(self._layers.info, div.firstChild); @@ -806,18 +801,18 @@ Map.prototype.setDiv = function(div) { div.offsetHeight; div.style.display = ''; - self.set("div", div); + self.set('div', div); - if (cordova.platform === "browser") { + if (cordova.platform === 'browser') { return; } - positionCSS = common.getStyle(div, "position"); - if (!positionCSS || positionCSS === "static") { - div.style.position = "relative"; + positionCSS = common.getStyle(div, 'position'); + if (!positionCSS || positionCSS === 'static') { + div.style.position = 'relative'; } - elemId = common.getPluginDomId(div); + var elemId = common.getPluginDomId(div); args.push(elemId); while (div.parentNode) { div.style.backgroundColor = 'rgba(0,0,0,0)'; @@ -835,7 +830,7 @@ Map.prototype.setDiv = function(div) { self.exec.call(self, function() { cordova.fireDocumentEvent('plugin_touch', { force: true, - action: "setDiv" + action: 'setDiv' }); self.refreshLayout(); }, self.errorHandler, self.id, 'setDiv', args, { @@ -849,7 +844,7 @@ Map.prototype.setDiv = function(div) { */ Map.prototype.getVisibleRegion = function(callback) { var self = this; - var cameraPosition = self.get("camera"); + var cameraPosition = self.get('camera'); if (!cameraPosition || !cameraPosition.southwest || !cameraPosition.northeast) { return null; } @@ -863,8 +858,8 @@ Map.prototype.getVisibleRegion = function(callback) { cameraPosition.nearRight ); - if (typeof callback === "function") { - console.log("[deprecated] getVisibleRegion() is changed. Please check out the https://goo.gl/yHstHQ"); + if (typeof callback === 'function') { + console.log('[deprecated] getVisibleRegion() is changed. Please check out the https://goo.gl/yHstHQ'); callback.call(self, latLngBounds); } return latLngBounds; @@ -876,7 +871,7 @@ Map.prototype.getVisibleRegion = function(callback) { Map.prototype.fromLatLngToPoint = function(latLng, callback) { var self = this; - if ("lat" in latLng && "lng" in latLng) { + if ('lat' in latLng && 'lng' in latLng) { var resolver = function(resolve, reject) { self.exec.call(self, @@ -885,17 +880,17 @@ Map.prototype.fromLatLngToPoint = function(latLng, callback) { self.id, 'fromLatLngToPoint', [latLng.lat, latLng.lng]); }; - if (typeof callback === "function") { + if (typeof callback === 'function') { resolver(callback, self.errorHandler); } else { return new Promise(resolver); } } else { var rejector = function(resolve, reject) { - reject("The latLng is invalid"); + reject('The latLng is invalid'); }; - if (typeof callback === "function") { + if (typeof callback === 'function') { rejector(callback, self.errorHandler); } else { return new Promise(rejector); @@ -908,7 +903,7 @@ Map.prototype.fromLatLngToPoint = function(latLng, callback) { */ Map.prototype.fromPointToLatLng = function(pixel, callback) { var self = this; - if (typeof pixel === "object" && "x" in pixel && "y" in pixel) { + if (typeof pixel === 'object' && 'x' in pixel && 'y' in pixel) { pixel = [pixel.x, pixel.y]; } if (pixel.length == 2 && utils.isArray(pixel)) { @@ -923,17 +918,17 @@ Map.prototype.fromPointToLatLng = function(pixel, callback) { self.id, 'fromPointToLatLng', [pixel[0], pixel[1]]); }; - if (typeof callback === "function") { + if (typeof callback === 'function') { resolver(callback, self.errorHandler); } else { return new Promise(resolver); } } else { var rejector = function(resolve, reject) { - reject("The pixel[] argument is invalid"); + reject('The pixel[] argument is invalid'); }; - if (typeof callback === "function") { + if (typeof callback === 'function') { rejector(callback, self.errorHandler); } else { return new Promise(rejector); @@ -949,40 +944,35 @@ Map.prototype.setPadding = function(p1, p2, p3, p4) { var padding = {}; padding.top = parseInt(p1, 10); switch (arguments.length) { - case 4: - // top right bottom left - padding.right = parseInt(p2, 10); - padding.bottom = parseInt(p3, 10); - padding.left = parseInt(p4, 10); - break; - - case 3: - // top right&left bottom - padding.right = parseInt(p2, 10); - padding.left = padding.right; - padding.bottom = parseInt(p3, 10); - break; - - case 2: - // top & bottom right&left - padding.bottom = parseInt(p1, 10); - padding.right = parseInt(p2, 10); - padding.left = padding.right; - break; - - case 1: - // top & bottom right & left - padding.bottom = padding.top; - padding.right = padding.top; - padding.left = padding.top; - break; + case 4: + // top right bottom left + padding.right = parseInt(p2, 10); + padding.bottom = parseInt(p3, 10); + padding.left = parseInt(p4, 10); + break; + + case 3: + // top right&left bottom + padding.right = parseInt(p2, 10); + padding.left = padding.right; + padding.bottom = parseInt(p3, 10); + break; + + case 2: + // top & bottom right&left + padding.bottom = parseInt(p1, 10); + padding.right = parseInt(p2, 10); + padding.left = padding.right; + break; + + case 1: + // top & bottom right & left + padding.bottom = padding.top; + padding.right = padding.top; + padding.left = padding.top; + break; } - this.exec.call(this, function(result) { - if (typeof callback === "function") { - var latLng = new LatLng(result[0] || 0, result[1] || 0); - callback.call(self, result); - } - }, self.errorHandler, this.id, 'setPadding', [padding]); + this.exec.call(this, null, self.errorHandler, this.id, 'setPadding', [padding]); return this; }; @@ -996,19 +986,19 @@ Map.prototype.addKmlOverlay = function(kmlOverlayOptions, callback) { if (kmlOverlayOptions.url) { - var link = document.createElement("a"); + var link = document.createElement('a'); link.href = kmlOverlayOptions.url; - kmlOverlayOptions.url = link.protocol+"//"+link.host+link.pathname + link.search; + kmlOverlayOptions.url = link.protocol+'//'+link.host+link.pathname + link.search; - var invisible_dot = self.get("invisible_dot"); + var invisible_dot = self.get('invisible_dot'); if (!invisible_dot || invisible_dot._isRemoved) { // Create an invisible marker for kmlOverlay - self.set("invisible_dot", self.addMarker({ + self.set('invisible_dot', self.addMarker({ position: { lat: 0, lng: 0 }, - icon: "skyblue", + icon: 'skyblue', visible: false })); } @@ -1023,22 +1013,22 @@ Map.prototype.addKmlOverlay = function(kmlOverlayOptions, callback) { if (kmlData instanceof BaseClass) { kmlData = new BaseArrayClass([kmlData]); } - var kmlId = "kmloverlay_" + Math.floor(Math.random() * Date.now()); + var kmlId = 'kmloverlay_' + Math.floor(Math.random() * Date.now()); var kmlOverlay = new KmlOverlay(self, kmlId, camera, kmlData, kmlOverlayOptions); self.OVERLAYS[kmlId] = kmlOverlay; resolve.call(self, kmlOverlay); - }); + }, reject); }; - if (typeof callback === "function") { + if (typeof callback === 'function') { resolver(callback, self.errorHandler); } else { return new Promise(resolver); } } else { - if (typeof callback === "function") { + if (typeof callback === 'function') { throw new Error('KML file url is required.'); } else { return Promise.reject('KML file url is required.'); @@ -1063,21 +1053,21 @@ Map.prototype.addFusionTableOverlay = function(fusionTableOptions, callback) { var fusionTableOverlay = new FusionTableOverlay(self, fusionTableOptions, exec); - if (cordova.platformId === "browser") { + if (cordova.platformId === 'browser') { //---------------------------------- // Browser: use FusionTable layer //---------------------------------- - self.exec.call(self, function(result) { + self.exec.call(self, function() { fusionTableOverlay._privateInitialize(); delete fusionTableOverlay._privateInitialize; - if (typeof callback === "function") { - callback.call(self, tileOverlay); + if (typeof callback === 'function') { + callback.call(self, fusionTableOverlay); } }, self.errorHandler, self.id, 'loadPlugin', ['FusionTableOverlay', fusionTableOptions, fusionTableOverlay.hashCode]); - if (typeof callback === "function") { + if (typeof callback === 'function') { callback(fusionTableOverlay); return; } else { @@ -1086,30 +1076,30 @@ Map.prototype.addFusionTableOverlay = function(fusionTableOptions, callback) { } - var query = ["select+", + var query = ['select+', fusionTableOptions.select, - "+from+", + '+from+', fusionTableOptions.from]; if (fusionTableOptions.where) { - query.push('+where+' + fusiontables.where); + query.push('+where+' + fusionTableOptions.where); } if (fusionTableOptions.orderBy) { - query.push('+orderBy+' + fusiontables.orderBy); + query.push('+orderBy+' + fusionTableOptions.orderBy); } if (fusionTableOptions.offset) { - query.push('+offset+' + fusiontables.offset); + query.push('+offset+' + fusionTableOptions.offset); } if (fusionTableOptions.limit) { - query.push('+limit+' + fusiontables.limit); + query.push('+limit+' + fusionTableOptions.limit); } else { query.push('+limit+1000'); } fusionTableOptions.url = - "https://fusiontables.google.com/exporttable\?query=" + + 'https://fusiontables.google.com/exporttable?query=' + query.join('') + - "&o=kml&g=" + fusionTableOptions.select + - "&styleId=2&templateId=2"; // including '&styleId=2&templateId=2', FusionTable exports the latest KML file + '&o=kml&g=' + fusionTableOptions.select + + '&styleId=2&templateId=2'; // including '&styleId=2&templateId=2', FusionTable exports the latest KML file fusionTableOptions.clickable = common.defaultTrueOption(fusionTableOptions.clickable); fusionTableOptions.suppressInfoWindows = fusionTableOptions.suppressInfoWindows === true; @@ -1136,16 +1126,16 @@ Map.prototype.addGroundOverlay = function(groundOverlayOptions, callback) { var groundOverlay = new GroundOverlay(self, groundOverlayOptions, exec); var groundOverlayId = groundOverlay.getId(); self.OVERLAYS[groundOverlayId] = groundOverlay; - groundOverlay.one(groundOverlayId + "_remove", function() { + groundOverlay.one(groundOverlayId + '_remove', function() { groundOverlay.off(); delete self.OVERLAYS[groundOverlayId]; groundOverlay = undefined; }); - self.exec.call(self, function(result) { + self.exec.call(self, function() { groundOverlay._privateInitialize(); delete groundOverlay._privateInitialize; - if (typeof callback === "function") { + if (typeof callback === 'function') { callback.call(self, groundOverlay); } }, self.errorHandler, self.id, 'loadPlugin', ['GroundOverlay', groundOverlayOptions, groundOverlay.hashCode]); @@ -1160,16 +1150,16 @@ Map.prototype.addTileOverlay = function(tilelayerOptions, callback) { var self = this; tilelayerOptions = tilelayerOptions || {}; tilelayerOptions.tileUrlFormat = tilelayerOptions.tileUrlFormat || null; - if (typeof tilelayerOptions.tileUrlFormat === "string") { - console.log("[deprecated] the tileUrlFormat property is now deprecated. Use the getTile property."); + if (typeof tilelayerOptions.tileUrlFormat === 'string') { + console.log('[deprecated] the tileUrlFormat property is now deprecated. Use the getTile property.'); tilelayerOptions.getTile = function(x, y, zoom) { return tilelayerOptions.tileUrlFormat.replace(//gi, x) .replace(//gi, y) .replace(//gi, zoom); }; } - if (typeof tilelayerOptions.getTile !== "function") { - throw new Error("[error] the getTile property is required."); + if (typeof tilelayerOptions.getTile !== 'function') { + throw new Error('[error] the getTile property is required.'); } tilelayerOptions.visible = common.defaultTrueOption(tilelayerOptions.visible); tilelayerOptions.zIndex = tilelayerOptions.zIndex || 0; @@ -1184,8 +1174,8 @@ Map.prototype.addTileOverlay = function(tilelayerOptions, callback) { self.OVERLAYS[tileOverlayId] = tileOverlay; var hashCode = tileOverlay.hashCode; - tileOverlay.one(tileOverlayId + "_remove", function() { - document.removeEventListener(tileOverlayId + "-" + hashCode + "-tileoverlay", onNativeCallback); + tileOverlay.one(tileOverlayId + '_remove', function() { + document.removeEventListener(tileOverlayId + '-' + hashCode + '-tileoverlay', onNativeCallback); tileOverlay.off(); delete self.OVERLAYS[tileOverlayId]; tileOverlay = undefined; @@ -1202,28 +1192,28 @@ Map.prototype.addTileOverlay = function(tilelayerOptions, callback) { var onNativeCallback = function(params) { var url = tilelayerOptions.getTile(params.x, params.y, params.zoom); - if (!url || url === "(null)" || url === "undefined" || url === "null") { - url = "(null)"; + if (!url || url === '(null)' || url === 'undefined' || url === 'null') { + url = '(null)'; } if (url instanceof Promise) { common.promiseTimeout(5000, url) .then(function(finalUrl) { - cordova_exec(null, self.errorHandler, self.id + "-tileoverlay", 'onGetTileUrlFromJS', [hashCode, params.key, finalUrl]); + cordova_exec(null, self.errorHandler, self.id + '-tileoverlay', 'onGetTileUrlFromJS', [hashCode, params.key, finalUrl]); }) .catch(function() { - cordova_exec(null, self.errorHandler, self.id + "-tileoverlay", 'onGetTileUrlFromJS', [hashCode, params.key, "(null)"]); + cordova_exec(null, self.errorHandler, self.id + '-tileoverlay', 'onGetTileUrlFromJS', [hashCode, params.key, '(null)']); }); } else { - cordova_exec(null, self.errorHandler, self.id + "-tileoverlay", 'onGetTileUrlFromJS', [hashCode, params.key, url]); + cordova_exec(null, self.errorHandler, self.id + '-tileoverlay', 'onGetTileUrlFromJS', [hashCode, params.key, url]); } }; - document.addEventListener(self.id + "-" + hashCode + "-tileoverlay", onNativeCallback); + document.addEventListener(self.id + '-' + hashCode + '-tileoverlay', onNativeCallback); - self.exec.call(self, function(result) { + self.exec.call(self, function() { tileOverlay._privateInitialize(); delete tileOverlay._privateInitialize; - if (typeof callback === "function") { + if (typeof callback === 'function') { callback.call(self, tileOverlay); } }, self.errorHandler, self.id, 'loadPlugin', ['TileOverlay', options, hashCode]); @@ -1249,18 +1239,18 @@ Map.prototype.addPolygon = function(polygonOptions, callback) { } return hole.map(function(position) { return { - "lat": position.lat, - "lng": position.lng + 'lat': position.lat, + 'lng': position.lng }; }); }); - polygonOptions.strokeColor = common.HTMLColor2RGBA(polygonOptions.strokeColor || "#FF000080", 0.75); + polygonOptions.strokeColor = common.HTMLColor2RGBA(polygonOptions.strokeColor || '#FF000080', 0.75); if (polygonOptions.fillColor) { - polygonOptions.fillColor = common.HTMLColor2RGBA(polygonOptions.fillColor || "#FF000080", 0.75); + polygonOptions.fillColor = common.HTMLColor2RGBA(polygonOptions.fillColor || '#FF000080', 0.75); } else { - polygonOptions.fillColor = common.HTMLColor2RGBA("#FF000080", 0.75); + polygonOptions.fillColor = common.HTMLColor2RGBA('#FF000080', 0.75); } - polygonOptions.strokeWidth = "strokeWidth" in polygonOptions ? polygonOptions.strokeWidth : 10; + polygonOptions.strokeWidth = 'strokeWidth' in polygonOptions ? polygonOptions.strokeWidth : 10; polygonOptions.visible = common.defaultTrueOption(polygonOptions.visible); polygonOptions.clickable = polygonOptions.clickable === true; polygonOptions.zIndex = polygonOptions.zIndex || 0; @@ -1271,20 +1261,20 @@ Map.prototype.addPolygon = function(polygonOptions, callback) { var polygon = new Polygon(self, polygonOptions, exec); var polygonId = polygon.getId(); self.OVERLAYS[polygonId] = polygon; - polygon.one(polygonId + "_remove", function() { + polygon.one(polygonId + '_remove', function() { polygon.off(); delete self.OVERLAYS[polygonId]; polygon = undefined; }); - self.exec.call(self, function(result) { + self.exec.call(self, function() { polygon._privateInitialize(); delete polygon._privateInitialize; - if (typeof callback === "function") { + if (typeof callback === 'function') { callback.call(self, polygon); } - }, self.errorHandler, self.id, 'loadPlugin', ["Polygon", opts, polygon.hashCode]); + }, self.errorHandler, self.id, 'loadPlugin', ['Polygon', opts, polygon.hashCode]); return polygon; }; @@ -1297,8 +1287,8 @@ Map.prototype.addPolyline = function(polylineOptions, callback) { polylineOptions.points = polylineOptions.points || []; var _orgs = polylineOptions.points; polylineOptions.points = common.convertToPositionArray(polylineOptions.points); - polylineOptions.color = common.HTMLColor2RGBA(polylineOptions.color || "#FF000080", 0.75); - polylineOptions.width = "width" in polylineOptions ? polylineOptions.width : 10; + polylineOptions.color = common.HTMLColor2RGBA(polylineOptions.color || '#FF000080', 0.75); + polylineOptions.width = 'width' in polylineOptions ? polylineOptions.width : 10; polylineOptions.visible = common.defaultTrueOption(polylineOptions.visible); polylineOptions.clickable = polylineOptions.clickable === true; polylineOptions.zIndex = polylineOptions.zIndex || 0; @@ -1310,17 +1300,17 @@ Map.prototype.addPolyline = function(polylineOptions, callback) { var polylineId = polyline.getId(); self.OVERLAYS[polylineId] = polyline; - polyline.one(polylineId + "_remove", function() { + polyline.one(polylineId + '_remove', function() { polyline.off(); delete self.OVERLAYS[polylineId]; polyline = undefined; }); - self.exec.call(self, function(result) { + self.exec.call(self, function() { polyline._privateInitialize(); delete polyline._privateInitialize; - if (typeof callback === "function") { + if (typeof callback === 'function') { callback.call(self, polyline); } }, self.errorHandler, self.id, 'loadPlugin', ['Polyline', opts, polyline.hashCode]); @@ -1336,27 +1326,27 @@ Map.prototype.addCircle = function(circleOptions, callback) { circleOptions.center = circleOptions.center || {}; circleOptions.center.lat = circleOptions.center.lat || 0.0; circleOptions.center.lng = circleOptions.center.lng || 0.0; - circleOptions.strokeColor = common.HTMLColor2RGBA(circleOptions.strokeColor || "#FF0000", 0.75); - circleOptions.fillColor = common.HTMLColor2RGBA(circleOptions.fillColor || "#000000", 0.75); - circleOptions.strokeWidth = "strokeWidth" in circleOptions ? circleOptions.strokeWidth : 10; + circleOptions.strokeColor = common.HTMLColor2RGBA(circleOptions.strokeColor || '#FF0000', 0.75); + circleOptions.fillColor = common.HTMLColor2RGBA(circleOptions.fillColor || '#000000', 0.75); + circleOptions.strokeWidth = 'strokeWidth' in circleOptions ? circleOptions.strokeWidth : 10; circleOptions.visible = common.defaultTrueOption(circleOptions.visible); circleOptions.zIndex = circleOptions.zIndex || 0; - circleOptions.radius = "radius" in circleOptions ? circleOptions.radius : 1; + circleOptions.radius = 'radius' in circleOptions ? circleOptions.radius : 1; var circle = new Circle(self, circleOptions, exec); var circleId = circle.getId(); self.OVERLAYS[circleId] = circle; - circle.one(circleId + "_remove", function() { + circle.one(circleId + '_remove', function() { circle.off(); delete self.OVERLAYS[circleId]; circle = undefined; }); - self.exec.call(self, function(result) { + self.exec.call(self, function() { circle._privateInitialize(); delete circle._privateInitialize; - if (typeof callback === "function") { + if (typeof callback === 'function') { callback.call(self, circle); } }, self.errorHandler, self.id, 'loadPlugin', ['Circle', circleOptions, circle.hashCode]); @@ -1387,7 +1377,7 @@ Map.prototype.addMarker = function(markerOptions, callback) { self.MARKERS[markerId] = marker; self.OVERLAYS[markerId] = marker; - marker.one(markerId + "_remove", function() { + marker.one(markerId + '_remove', function() { delete self.MARKERS[markerId]; delete self.OVERLAYS[markerId]; marker.destroy(); @@ -1407,7 +1397,7 @@ Map.prototype.addMarker = function(markerOptions, callback) { marker._privateInitialize(markerOptions); delete marker._privateInitialize; - if (typeof callback === "function") { + if (typeof callback === 'function') { callback.call(self, marker); } }, self.errorHandler, self.id, 'loadPlugin', ['Marker', markerOptions, marker.hashCode]); @@ -1421,7 +1411,7 @@ Map.prototype.addMarker = function(markerOptions, callback) { //------------------ Map.prototype.addMarkerCluster = function(markerClusterOptions, callback) { var self = this; - if (typeof markerClusterOptions === "function") { + if (typeof markerClusterOptions === 'function') { callback = markerClusterOptions; markerClusterOptions = null; } @@ -1431,12 +1421,12 @@ Map.prototype.addMarkerCluster = function(markerClusterOptions, callback) { }); var markerCluster = new MarkerCluster(self, { - "icons": markerClusterOptions.icons, - //"markerMap": markerMap, - "idxCount": positionList.length + 1, - "maxZoomLevel": Math.min(markerClusterOptions.maxZoomLevel || 15, 18), - "debug": markerClusterOptions.debug === true, - "boundsDraw": common.defaultTrueOption(markerClusterOptions.boundsDraw) + 'icons': markerClusterOptions.icons, + //'markerMap': markerMap, + 'idxCount': positionList.length + 1, + 'maxZoomLevel': Math.min(markerClusterOptions.maxZoomLevel || 15, 18), + 'debug': markerClusterOptions.debug === true, + 'boundsDraw': common.defaultTrueOption(markerClusterOptions.boundsDraw) }, exec); var markerClusterId = markerCluster.getId(); self.OVERLAYS[markerClusterId] = markerCluster; @@ -1448,8 +1438,8 @@ Map.prototype.addMarkerCluster = function(markerClusterOptions, callback) { var markerOptions = markerClusterOptions.markers[idx]; markerOptions = common.markerOptionsFilter(markerOptions); - var markerId = markerOptions.id || "marker_" + idx; - //markerId = result.id + "-" + markerId; + var markerId = markerOptions.id || 'marker_' + idx; + //markerId = result.id + '-' + markerId; markerOptions.__pgmId = markerId; markerOptions._cluster = { isRemoved: false, @@ -1458,12 +1448,12 @@ Map.prototype.addMarkerCluster = function(markerClusterOptions, callback) { _marker: null }; /* - var marker = new Marker(self, markerId, markerOptions, "MarkerCluster", exec); - marker.set("isAdded", false, true); - marker.set("geocell", geocell, true); - marker.set("position", markerOptions.position, true); + var marker = new Marker(self, markerId, markerOptions, 'MarkerCluster', exec); + marker.set('isAdded', false, true); + marker.set('geocell', geocell, true); + marker.set('position', markerOptions.position, true); marker.getId = function() { - return result.id + "-" + markerId; + return result.id + '-' + markerId; }; */ markerMap[markerId] = markerOptions; @@ -1472,17 +1462,17 @@ Map.prototype.addMarkerCluster = function(markerClusterOptions, callback) { //self.OVERLAYS[marker.getId()] = marker; }); - Object.defineProperty(markerCluster, "_markerMap", { + Object.defineProperty(markerCluster, '_markerMap', { value: markerMap, writable: false }); - markerCluster.one("remove", function() { + markerCluster.one('remove', function() { delete self.OVERLAYS[result.id]; /* result.geocellList.forEach(function(geocell, idx) { var markerOptions = markerClusterOptions.markers[idx]; - var markerId = result.id + "-" + (markerOptions.id || "marker_" + idx); + var markerId = result.id + '-' + (markerOptions.id || 'marker_' + idx); var marker = self.MARKERS[markerId]; if (marker) { marker.off(); @@ -1501,12 +1491,12 @@ Map.prototype.addMarkerCluster = function(markerClusterOptions, callback) { force: true }); - if (typeof callback === "function") { + if (typeof callback === 'function') { callback.call(self, markerCluster); } }, self.errorHandler, self.id, 'loadPlugin', ['MarkerCluster', { - "positionList": positionList, - "debug": markerClusterOptions.debug === true + 'positionList': positionList, + 'debug': markerClusterOptions.debug === true }, markerCluster.hashCode]); return markerCluster; @@ -1517,7 +1507,7 @@ Map.prototype.addMarkerCluster = function(markerClusterOptions, callback) { *****************************************************************************/ Map.prototype._onSyncInfoWndPosition = function(eventName, points) { - this.set("infoPosition", points); + this.set('infoPosition', points); }; Map.prototype._onMapEvent = function(eventName) { @@ -1538,10 +1528,10 @@ Map.prototype._onMarkerEvent = function(eventName, markerId, position) { if (marker) { marker.set('position', position); if (eventName === event.INFO_OPEN) { - marker.set("isInfoWindowVisible", true); + marker.set('isInfoWindowVisible', true); } if (eventName === event.INFO_CLOSE) { - marker.set("isInfoWindowVisible", false); + marker.set('isInfoWindowVisible', false); } marker.trigger(eventName, position, marker); } @@ -1558,10 +1548,10 @@ Map.prototype._onClusterEvent = function(eventName, markerClusterId, clusterId, markerCluster.trigger(eventName, position, marker); } else { if (eventName === event.INFO_OPEN) { - marker.set("isInfoWindowVisible", true); + marker.set('isInfoWindowVisible', true); } if (eventName === event.INFO_CLOSE) { - marker.set("isInfoWindowVisible", false); + marker.set('isInfoWindowVisible', false); } } marker.trigger(eventName, position, marker); @@ -1571,7 +1561,7 @@ Map.prototype._onClusterEvent = function(eventName, markerClusterId, clusterId, if (cluster) { markerCluster.trigger(eventName, cluster); } else { - console.log("-----> This is remained cluster icon : " + clusterId); + console.log('-----> This is remained cluster icon : ' + clusterId); } } } @@ -1591,17 +1581,17 @@ Map.prototype._onOverlayEvent = function(eventName, overlayId) { }; Map.prototype.getCameraTarget = function() { - return this.get("camera_target"); + return this.get('camera_target'); }; Map.prototype.getCameraZoom = function() { - return this.get("camera_zoom"); + return this.get('camera_zoom'); }; Map.prototype.getCameraTilt = function() { - return this.get("camera_tilt"); + return this.get('camera_tilt'); }; Map.prototype.getCameraBearing = function() { - return this.get("camera_bearing"); + return this.get('camera_bearing'); }; Map.prototype._onCameraEvent = function(eventName, cameraPosition) { diff --git a/www/MapTypeId.js b/www/MapTypeId.js index 507d38da5..aa6862add 100644 --- a/www/MapTypeId.js +++ b/www/MapTypeId.js @@ -1,8 +1,8 @@ module.exports = { - 'NORMAL': 'MAP_TYPE_NORMAL', - 'ROADMAP': 'MAP_TYPE_NORMAL', - 'SATELLITE': 'MAP_TYPE_SATELLITE', - 'HYBRID': 'MAP_TYPE_HYBRID', - 'TERRAIN': 'MAP_TYPE_TERRAIN', - 'NONE': 'MAP_TYPE_NONE' + 'NORMAL': 'MAP_TYPE_NORMAL', + 'ROADMAP': 'MAP_TYPE_NORMAL', + 'SATELLITE': 'MAP_TYPE_SATELLITE', + 'HYBRID': 'MAP_TYPE_HYBRID', + 'TERRAIN': 'MAP_TYPE_TERRAIN', + 'NONE': 'MAP_TYPE_NONE' }; diff --git a/www/Marker.js b/www/Marker.js index 5473f59fc..e30cd16b6 100644 --- a/www/Marker.js +++ b/www/Marker.js @@ -1,5 +1,4 @@ -var argscheck = require('cordova/argscheck'), - utils = require('cordova/utils'), +var utils = require('cordova/utils'), common = require('./Common'), LatLng = require('./LatLng'), event = require('./event'), @@ -27,69 +26,69 @@ var Marker = function(map, markerOptions, _exec, extras) { self.showInfoWindow.apply(self); }); - self.on("position_changed", function() { - var position = self.get("position"); + self.on('position_changed', function() { + var position = self.get('position'); position.lat = parseFloat(position.lat, 10); position.lng = parseFloat(position.lng, 10); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setPosition', [self.getId(), position.lat, position.lng]); }); - self.on("rotation_changed", function() { - var rotation = self.get("rotation"); + self.on('rotation_changed', function() { + var rotation = self.get('rotation'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setRotation', [self.getId(), rotation]); }); - self.on("snippet_changed", function() { - var snippet = self.get("snippet"); + self.on('snippet_changed', function() { + var snippet = self.get('snippet'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setSnippet', [self.getId(), snippet]); }); - self.on("visible_changed", function() { - var visible = self.get("visible"); + self.on('visible_changed', function() { + var visible = self.get('visible'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setVisible', [self.getId(), visible]); }); - self.on("title_changed", function() { - var title = self.get("title"); + self.on('title_changed', function() { + var title = self.get('title'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setTitle', [self.getId(), title]); }); - self.on("icon_changed", function() { - var icon = self.get("icon"); + self.on('icon_changed', function() { + var icon = self.get('icon'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setIcon', [self.getId(), icon]); }); - self.on("flat_changed", function() { - var flat = self.get("flat"); + self.on('flat_changed', function() { + var flat = self.get('flat'); flat = flat === true; self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setFlat', [self.getId(), flat]); }); - self.on("draggable_changed", function() { - var draggable = self.get("draggable"); + self.on('draggable_changed', function() { + var draggable = self.get('draggable'); draggable = draggable === true; self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setDraggable', [self.getId(), draggable]); }); - self.on("anchor_changed", function() { - var anchor = self.get("anchor"); + self.on('anchor_changed', function() { + var anchor = self.get('anchor'); if (!anchor) { return; } self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setIconAnchor', [self.getId(), anchor[0], anchor[1]]); }); - self.on("infoWindowAnchor_changed", function() { - var anchor = self.get("infoWindowAnchor"); + self.on('infoWindowAnchor_changed', function() { + var anchor = self.get('infoWindowAnchor'); if (!anchor) { return; } self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setInfoWindowAnchor', [self.getId(), anchor[0], anchor[1]]); }); - self.on("zIndex_changed", function() { - var zIndex = self.get("zIndex"); + self.on('zIndex_changed', function() { + var zIndex = self.get('zIndex'); if (zIndex === null || zIndex === undefined) { return; } self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setZIndex', [self.getId(), zIndex]); }); - self.on("opacity_changed", function() { - var opacity = self.get("opacity"); + self.on('opacity_changed', function() { + var opacity = self.get('opacity'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setOpacity', [self.getId(), opacity]); }); - self.on("disableAutoPan_changed", function() { - var disableAutoPan = self.get("disableAutoPan"); + self.on('disableAutoPan_changed', function() { + var disableAutoPan = self.get('disableAutoPan'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setDisableAutoPan', [self.getId(), disableAutoPan]); }); @@ -100,18 +99,18 @@ utils.extend(Marker, Overlay); Marker.prototype.remove = function(callback) { var self = this; if (self._isRemoved) { - if (typeof callback === "function") { + if (typeof callback === 'function') { return; } else { return Promise.resolve(); } } - Object.defineProperty(self, "_isRemoved", { + Object.defineProperty(self, '_isRemoved', { value: true, writable: false }); self.trigger(event.INFO_CLOSE); // close open infowindow, otherwise it will stay - self.trigger(self.id + "_remove"); + self.trigger(self.id + '_remove'); var resolver = function(resolve, reject) { self.exec.call(self, @@ -125,7 +124,7 @@ Marker.prototype.remove = function(callback) { }); }; - if (typeof callback === "function") { + if (typeof callback === 'function') { resolver(callback, self.errorHandler); } else { return new Promise(resolver); @@ -137,19 +136,19 @@ Marker.prototype.remove = function(callback) { Marker.prototype.getOptions = function() { var self = this; return { - "id": self.getId(), - "position": self.getPosition(), - "disableAutoPan": self.get("disableAutoPan"), - "opacity": self.get("opacity"), - "icon": self.get("icon"), - "zIndex": self.get("zIndex"), - "anchor": self.get("anchor"), - "infoWindowAnchor": self.get("infoWindowAnchor"), - "draggable": self.get("draggable"), - "title": self.getTitle(), - "snippet": self.getSnippet(), - "visible": self.get("visible"), - "rotation": self.getRotation() + 'id': self.getId(), + 'position': self.getPosition(), + 'disableAutoPan': self.get('disableAutoPan'), + 'opacity': self.get('opacity'), + 'icon': self.get('icon'), + 'zIndex': self.get('zIndex'), + 'anchor': self.get('anchor'), + 'infoWindowAnchor': self.get('infoWindowAnchor'), + 'draggable': self.get('draggable'), + 'title': self.getTitle(), + 'snippet': self.getSnippet(), + 'visible': self.get('visible'), + 'rotation': self.getRotation() }; }; Marker.prototype.getPosition = function() { @@ -166,13 +165,13 @@ Marker.prototype.setAnimation = function(animation, callback) { animation = animation || null; if (!animation) { // just ignore - if (typeof callback === "function") { + if (typeof callback === 'function') { return self; } else { return Promise.resolve(); } } - self.set("animation", animation); + self.set('animation', animation); var resolver = function(resolve, reject) { self.exec.call(self, @@ -181,7 +180,7 @@ Marker.prototype.setAnimation = function(animation, callback) { self.getPluginName(), 'setAnimation', [self.getId(), animation]); }; - if (typeof callback === "function") { + if (typeof callback === 'function') { resolver(callback, self.errorHandler); return self; } else { @@ -246,15 +245,15 @@ Marker.prototype.setTitle = function(title) { console.log('missing value for title'); return this; } - title = "" + title; // Convert to strings mandatory + title = '' + title; // Convert to strings mandatory this.set('title', title); return this; }; Marker.prototype.setVisible = function(visible) { visible = common.parseBoolean(visible); this.set('visible', visible); - if (!visible && this.map.get("active_marker_id") === this.id) { - this.map.set("active_marker_id", undefined); + if (!visible && this.map.get('active_marker_id') === this.id) { + this.map.set('active_marker_id', undefined); } return this; }; @@ -269,7 +268,7 @@ Marker.prototype.getSnippet = function() { return this.get('snippet'); }; Marker.prototype.setRotation = function(rotation) { - if (typeof rotation !== "number") { + if (typeof rotation !== 'number') { console.log('missing value for rotation'); return false; } @@ -281,13 +280,13 @@ Marker.prototype.getRotation = function() { }; Marker.prototype.showInfoWindow = function() { var self = this; - //if (!self.get("title") && !self.get("snippet") || - // self.get("isInfoWindowVisible")) { - if (!self.get("title") && !self.get("snippet")) { + //if (!self.get('title') && !self.get('snippet') || + // self.get('isInfoWindowVisible')) { + if (!self.get('title') && !self.get('snippet')) { return; } - self.set("isInfoWindowVisible", true); - self.map.set("active_marker_id", self.id); + self.set('isInfoWindowVisible', true); + self.map.set('active_marker_id', self.id); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'showInfoWindow', [self.getId()], { sync: true }); @@ -295,11 +294,11 @@ Marker.prototype.showInfoWindow = function() { }; Marker.prototype.hideInfoWindow = function() { var self = this; - if (self.map.get("active_marker_id") === self.id) { - self.map.set("active_marker_id", null); + if (self.map.get('active_marker_id') === self.id) { + self.map.set('active_marker_id', null); } - if (self.get("isInfoWindowVisible")) { - self.set("isInfoWindowVisible", false); + if (self.get('isInfoWindowVisible')) { + self.set('isInfoWindowVisible', false); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'hideInfoWindow', [self.getId()], { sync: true }); @@ -307,10 +306,10 @@ Marker.prototype.hideInfoWindow = function() { return self; }; Marker.prototype.isInfoWindowShown = function() { - return this.get("isInfoWindowVisible") === true; + return this.get('isInfoWindowVisible') === true; }; Marker.prototype.isVisible = function() { - return this.get("visible") === true; + return this.get('visible') === true; }; Marker.prototype.setPosition = function(position) { diff --git a/www/MarkerCluster.js b/www/MarkerCluster.js index 17a85b83e..c443be6de 100644 --- a/www/MarkerCluster.js +++ b/www/MarkerCluster.js @@ -1,10 +1,7 @@ -var argscheck = require('cordova/argscheck'), - utils = require('cordova/utils'), +var utils = require('cordova/utils'), common = require('./Common'), event = require('./event'), geomodel = require('./geomodel'), - LatLng = require('./LatLng'), - LatLngBounds = require('./LatLngBounds'), Marker = require('./Marker'), Cluster = require('./Cluster'), spherical = require('./spherical'), @@ -15,42 +12,42 @@ var argscheck = require('cordova/argscheck'), * MarkerCluster Class *****************************************************************************/ var exec; -var MarkerCluster = function(map, markerClusterOptions, _exec) { +var MarkerCluster = function (map, markerClusterOptions, _exec) { exec = _exec; Overlay.call(this, map, markerClusterOptions, 'MarkerCluster', _exec); var idxCount = markerClusterOptions.idxCount; var self = this; - Object.defineProperty(self, "maxZoomLevel", { + Object.defineProperty(self, 'maxZoomLevel', { value: markerClusterOptions.maxZoomLevel, writable: false }); - Object.defineProperty(self, "_clusterBounds", { + Object.defineProperty(self, '_clusterBounds', { value: new BaseArrayClass(), writable: false }); - Object.defineProperty(self, "_geocellBounds", { + Object.defineProperty(self, '_geocellBounds', { value: {}, writable: false }); - Object.defineProperty(self, "_clusters", { + Object.defineProperty(self, '_clusters', { value: {}, writable: false }); - Object.defineProperty(self, "debug", { + Object.defineProperty(self, 'debug', { value: markerClusterOptions.debug === true, writable: false }); - Object.defineProperty(self, "MAX_RESOLUTION", { + Object.defineProperty(self, 'MAX_RESOLUTION', { value: 11, writable: false }); - Object.defineProperty(self, "OUT_OF_RESOLUTION", { + Object.defineProperty(self, 'OUT_OF_RESOLUTION', { value: 999, writable: false }); - Object.defineProperty(self, "boundsDraw", { + Object.defineProperty(self, 'boundsDraw', { value: markerClusterOptions.boundsDraw === true, writable: false }); @@ -59,14 +56,26 @@ var MarkerCluster = function(map, markerClusterOptions, _exec) { self.map.addPolygon({ visible: false, points: [ - {lat: 0, lng: 0}, - {lat: 0, lng: 0}, - {lat: 0, lng: 0}, - {lat: 0, lng: 0} + { + lat: 0, + lng: 0 + }, + { + lat: 0, + lng: 0 + }, + { + lat: 0, + lng: 0 + }, + { + lat: 0, + lng: 0 + } ], strokeWidth: 1 - }, function(polygon) { - self.set("polygon", polygon); + }, function (polygon) { + self.set('polygon', polygon); }); } self.taskQueue = []; @@ -83,36 +92,35 @@ var MarkerCluster = function(map, markerClusterOptions, _exec) { continue; } if (icons[i].anchor && - typeof icons[i].anchor === "object" && - "x" in icons[i].anchor && - "y" in icons[i].anchor) { + typeof icons[i].anchor === 'object' && + 'x' in icons[i].anchor && + 'y' in icons[i].anchor) { icons[i].anchor = [icons[i].anchor.x, icons[i].anchor.y]; } if (icons[i].infoWindowAnchor && - typeof icons[i].infoWindowAnchor === "object" && - "x" in icons[i].infoWindowAnchor && - "y" in icons[i].infoWindowAnchor) { + typeof icons[i].infoWindowAnchor === 'object' && + 'x' in icons[i].infoWindowAnchor && + 'y' in icons[i].infoWindowAnchor) { icons[i].infoWindowAnchor = [icons[i].infoWindowAnchor.x, icons[i].infoWindowAnchor.anchor.y]; } if (icons[i].label && common.isHTMLColorString(icons[i].label.color)) { - icons[i].label.color = common.HTMLColor2RGBA(icons[i].label.color); + icons[i].label.color = common.HTMLColor2RGBA(icons[i].label.color); } } - Object.defineProperty(self, "icons", { - value: icons, - writable: false + Object.defineProperty(self, 'icons', { + value: icons, + writable: false }); - self.addMarker = function(markerOptions, skipRedraw) { + self.addMarker = function (markerOptions, skipRedraw) { idxCount++; - var resolution = self.get("resolution"); markerOptions = common.markerOptionsFilter(markerOptions); var geocell = geomodel.getGeocell(markerOptions.position.lat, markerOptions.position.lng, self.MAX_RESOLUTION + 1); - var markerId = (markerOptions.__pgmId || "marker_" + idxCount); + var markerId = (markerOptions.__pgmId || 'marker_' + idxCount); markerOptions.__pgmId = markerId; markerOptions._cluster = { isRemoved: false, @@ -121,10 +129,10 @@ var MarkerCluster = function(map, markerClusterOptions, _exec) { _marker: null }; - //var marker = new Marker(self, markerId, markerOptions, "markercluster"); + //var marker = new Marker(self, markerId, markerOptions, 'markercluster'); //marker._cluster.isAdded = false; - //marker.set("geocell", geocell, true); - //marker.set("position", markerOptions.position, true); + //marker.set('geocell', geocell, true); + //marker.set('position', markerOptions.position, true); self._markerMap[markerId] = markerOptions; if (skipRedraw || !self._isReady) { return; @@ -133,7 +141,7 @@ var MarkerCluster = function(map, markerClusterOptions, _exec) { force: true }); }; - self.addMarkers = function(markers) { + self.addMarkers = function (markers) { if (utils.isArray(markers) || Array.isArray(markers)) { for (var i = 0; i < markers.length; i++) { self.addMarker(markers[i], true); @@ -148,13 +156,13 @@ var MarkerCluster = function(map, markerClusterOptions, _exec) { }; map.on(event.CAMERA_MOVE_END, self._onCameraMoved.bind(self)); - window.addEventListener("orientationchange", self._onCameraMoved.bind(self)); + window.addEventListener('orientationchange', self._onCameraMoved.bind(self)); - self.on("cluster_click", self.onClusterClicked); - self.on("nextTask", function(){ + self.on('cluster_click', self.onClusterClicked); + self.on('nextTask', function () { self._isWorking = false; if (self._stopRequest || self._isRemoved || - self.taskQueue.length === 0 || !self._isReady) { + self.taskQueue.length === 0 || !self._isReady) { return; } self.redraw.call(self); @@ -165,8 +173,8 @@ var MarkerCluster = function(map, markerClusterOptions, _exec) { // }); if (self.debug) { - self.debugTimer = setInterval(function() { - console.log("self.taskQueue.push = " + self.taskQueue.length); + self.debugTimer = setInterval(function () { + console.log('self.taskQueue.push = ' + self.taskQueue.length); }, 5000); } @@ -175,35 +183,41 @@ var MarkerCluster = function(map, markerClusterOptions, _exec) { utils.extend(MarkerCluster, Overlay); -MarkerCluster.prototype.onClusterClicked = function(cluster) { +MarkerCluster.prototype.onClusterClicked = function (cluster) { if (this._isRemoved) { return null; } var self = this; - var polygon = self.get("polygon"); + var polygon = self.get('polygon'); var bounds = cluster.getBounds(); if (self.boundsDraw) { polygon.setPoints([ bounds.southwest, - {lat: bounds.northeast.lat, lng: bounds.southwest.lng}, + { + lat: bounds.northeast.lat, + lng: bounds.southwest.lng + }, bounds.northeast, - {lat: bounds.southwest.lat, lng: bounds.northeast.lng} + { + lat: bounds.southwest.lat, + lng: bounds.northeast.lng + } ]); polygon.setVisible(true); } this.map.animateCamera({ target: cluster.getBounds(), duration: 500 - }, function() { + }, function () { if (self.boundsDraw) { - setTimeout(function() { + setTimeout(function () { polygon.setVisible(false); }, 500); } }); }; -MarkerCluster.prototype._onCameraMoved = function() { +MarkerCluster.prototype._onCameraMoved = function () { var self = this; if (self._isRemoved || self._stopRequest || !self._isReady) { @@ -216,11 +230,11 @@ MarkerCluster.prototype._onCameraMoved = function() { }; -MarkerCluster.prototype.remove = function(callback) { +MarkerCluster.prototype.remove = function (callback) { var self = this; self._stopRequest = self.hashCode; if (self._isRemoved) { - if (typeof callback === "function") { + if (typeof callback === 'function') { return; } else { return Promise.resolve(); @@ -230,7 +244,7 @@ MarkerCluster.prototype.remove = function(callback) { clearInterval(self.debugTimer); self.self.debugTimer = undefined; } - self._redraw = function(){}; + self._redraw = function () {}; if (self._isWorking) { setTimeout(arguments.callee.bind(self), 20); @@ -238,18 +252,19 @@ MarkerCluster.prototype.remove = function(callback) { } var keys; - var resolution = self.get("resolution"), - activeMarker = self.map.get("active_marker"), + var resolution = self.get('resolution'), + activeMarker = self.map.get('active_marker'), deleteClusters = []; self.taskQueue = []; - Object.defineProperty(self, "_isRemoved", { - value: true, - writable: false + Object.defineProperty(self, '_isRemoved', { + value: true, + writable: false }); - self.trigger("remove"); + self.trigger('remove'); var activeMarkerId = activeMarker ? activeMarker.getId() : null; + var markerOpts; if (resolution === self.OUT_OF_RESOLUTION) { while (self._clusters[resolution].length > 0) { markerOpts = self._clusters[resolution].shift(); @@ -266,11 +281,11 @@ MarkerCluster.prototype.remove = function(callback) { } } else if (self._clusters[resolution]) { keys = Object.keys(self._clusters[resolution]); - keys.forEach(function(geocell) { + keys.forEach(function (geocell) { var cluster = self._clusters[resolution][geocell]; var noClusterMode = cluster.getMode() === cluster.NO_CLUSTER_MODE; if (noClusterMode) { - cluster.getMarkers().forEach(function(markerOpts, idx) { + cluster.getMarkers().forEach(function (markerOpts) { if (markerOpts.__pgmId === activeMarkerId) { var marker = markerOpts._cluster.marker; if (!marker) { @@ -290,40 +305,41 @@ MarkerCluster.prototype.remove = function(callback) { }); } - - var resolver = function(resolve, reject) { + var resolver = function (resolve, reject) { self.exec.call(self, resolve.bind(self), reject.bind(self), - self.getPluginName(), 'remove', [self.getId()], - {sync: true, remove: true}); + self.getPluginName(), 'remove', [self.getId()], { + sync: true, + remove: true + }); }; var answer; - if (typeof callback === "function") { + if (typeof callback === 'function') { resolver(callback, self.errorHandler); } else { - result = new Promise(resolver); + answer = new Promise(resolver); } keys = Object.keys(self._markerMap); - keys.forEach(function(markerId) { + keys.forEach(function (markerId) { delete self._markerMap[markerId]._cluster; }); - if (self.boundsDraw && self.get("polygon")) { - self.get("polygon").remove(); + if (self.boundsDraw && self.get('polygon')) { + self.get('polygon').remove(); } self.off(); return answer; }; -MarkerCluster.prototype.removeMarkerById = function(markerId) { +MarkerCluster.prototype.removeMarkerById = function (markerId) { var self = this; if (self._isRemoved) { return null; } - //if (markerId.indexOf(self.id + "-") === -1) { - // markerId = self.id + "-" + markerId; + //if (markerId.indexOf(self.id + '-') === -1) { + // markerId = self.id + '-' + markerId; //} var markerOpts = self._markerMap[markerId]; if (!markerOpts) { @@ -355,17 +371,19 @@ MarkerCluster.prototype.removeMarkerById = function(markerId) { //delete self._markerMap[markerId]; if (isAdded) { self.exec.call(self, null, null, self.getPluginName(), 'redrawClusters', [self.getId(), { - "delete": [markerId] - }], {sync: true}); + 'delete': [markerId] + }], { + sync: true + }); } }; -MarkerCluster.prototype.getMarkerById = function(markerId) { +MarkerCluster.prototype.getMarkerById = function (markerId) { var self = this; if (self._isRemoved) { return null; } - //if (markerId.indexOf(self.id + "-") === -1) { - // markerId = self.id + "-" + markerId; + //if (markerId.indexOf(self.id + '-') === -1) { + // markerId = self.id + '-' + markerId; //} var markerOpts = self._markerMap[markerId]; if (!markerOpts) { @@ -379,13 +397,13 @@ MarkerCluster.prototype.getMarkerById = function(markerId) { return marker; }; -MarkerCluster.prototype.getClusterByClusterId = function(clusterId) { +MarkerCluster.prototype.getClusterByClusterId = function (clusterId) { var self = this; if (self._isRemoved) { return null; } - var resolution = self.get("resolution"); + var resolution = self.get('resolution'); if (!self._clusters[resolution]) { return null; @@ -395,8 +413,7 @@ MarkerCluster.prototype.getClusterByClusterId = function(clusterId) { return cluster; }; - -MarkerCluster.prototype.redraw = function(params) { +MarkerCluster.prototype.redraw = function (params) { var self = this; if (self._isRemoved || self._stopRequest || !self._isReady) { return null; @@ -404,16 +421,16 @@ MarkerCluster.prototype.redraw = function(params) { self.taskQueue.push(params); if (self.debug) { - console.log("self.taskQueue.push = " + self.taskQueue.length); + console.log('self.taskQueue.push = ' + self.taskQueue.length); } if (self._isRemoved || self._stopRequest || self.taskQueue.length > 1) { return; } if (self.debug) { - self._clusterBounds.forEach(function(polyline, cb) { + self._clusterBounds.forEach(function (polyline, cb) { polyline.remove(); cb(); - }, function() { + }, function () { self._clusterBounds.empty(); var taskParams = self.taskQueue.pop(); self.taskQueue.length = 0; @@ -434,19 +451,18 @@ MarkerCluster.prototype.redraw = function(params) { }); } }; -MarkerCluster.prototype._redraw = function(params) { +MarkerCluster.prototype._redraw = function (params) { var self = this; if (self._isRemoved || self._stopRequest || self._isWorking || !self._isReady) { return null; } self._isWorking = true; - var map = self.map, - currentZoomLevel = self.map.getCameraZoom(), - prevResolution = self.get("resolution"); + var currentZoomLevel = self.map.getCameraZoom(), + prevResolution = self.get('resolution'); currentZoomLevel = currentZoomLevel < 0 ? 0 : currentZoomLevel; - self.set("zoom", currentZoomLevel); + self.set('zoom', currentZoomLevel); var resolution = 1; resolution = self.maxZoomLevel > 3 && currentZoomLevel > 3 ? 2 : resolution; @@ -467,8 +483,8 @@ MarkerCluster.prototype._redraw = function(params) { //------------------------------------------------------------------------ var cellLen = resolution + 1; - var prevSWcell = self.get("prevSWcell"); - var prevNEcell = self.get("prevNEcell"); + var prevSWcell = self.get('prevSWcell'); + var prevNEcell = self.get('prevNEcell'); var distanceA = spherical.computeDistanceBetween(params.visibleRegion.farRight, params.visibleRegion.farLeft); var distanceB = spherical.computeDistanceBetween(params.visibleRegion.farRight, params.visibleRegion.nearRight); @@ -481,7 +497,7 @@ MarkerCluster.prototype._redraw = function(params) { if (!params.force && prevSWcell === swCell && prevNEcell === neCell) { - self.trigger("nextTask"); + self.trigger('nextTask'); return; } var nwCell = geomodel.getGeocell(expandedRegion.northeast.lat, expandedRegion.southwest.lng, cellLen); @@ -490,8 +506,8 @@ MarkerCluster.prototype._redraw = function(params) { if (currentZoomLevel > self.maxZoomLevel || resolution === 0) { resolution = self.OUT_OF_RESOLUTION; } - self.set("resolution", resolution); - //console.log("--->prevResolution = " + prevResolution + ", resolution = " + resolution); + self.set('resolution', resolution); + //console.log('--->prevResolution = ' + prevResolution + ', resolution = ' + resolution); var targetMarkers = []; @@ -512,17 +528,23 @@ MarkerCluster.prototype._redraw = function(params) { var ignoreGeocells = []; var allowGeocells = [swCell, neCell, nwCell, seCell]; - var pos, prevCell = "", cell; + var pos, cell; var coners = [ expandedRegion.northeast, - {lat: expandedRegion.northeast.lat, lng: expandedRegion.southwest.lng}, + { + lat: expandedRegion.northeast.lat, + lng: expandedRegion.southwest.lng + }, expandedRegion.southwest, - {lat: expandedRegion.southwest.lat, lng: expandedRegion.northeast.lng}, + { + lat: expandedRegion.southwest.lat, + lng: expandedRegion.northeast.lng + }, expandedRegion.northeast ]; for (j = 0; j < 4; j++) { - for (i = 0.25; i < 1; i+= 0.25) { - pos = plugin.google.maps.geometry.spherical.interpolate(coners[j], coners[j + 1], i); + for (i = 0.25; i < 1; i += 0.25) { + pos = window.plugin.google.maps.geometry.spherical.interpolate(coners[j], coners[j + 1], i); cell = geomodel.getGeocell(pos.lat, pos.lng, cellLen); if (allowGeocells.indexOf(cell) === -1) { @@ -531,8 +553,8 @@ MarkerCluster.prototype._redraw = function(params) { } } - //console.log("---->548"); - var activeMarker = self.map.get("active_marker"); + //console.log('---->548'); + var activeMarker = self.map.get('active_marker'); var activeMarkerId = activeMarker ? activeMarker.getId() : null; if (prevResolution === self.OUT_OF_RESOLUTION) { if (resolution === self.OUT_OF_RESOLUTION) { @@ -540,12 +562,12 @@ MarkerCluster.prototype._redraw = function(params) { // Just camera move, no zoom changed //-------------------------------------- keys = Object.keys(self._markerMap); - keys.forEach(function(markerId) { + keys.forEach(function (markerId) { var markerOpts = self._markerMap[markerId]; if (self._isRemoved || - self._stopRequest || - markerOpts._cluster.isRemoved || - markerOpts._cluster.isAdded) { + self._stopRequest || + markerOpts._cluster.isRemoved || + markerOpts._cluster.isAdded) { return; } @@ -570,28 +592,29 @@ MarkerCluster.prototype._redraw = function(params) { //-------------- // zoom out //-------------- - while(self._clusters[self.OUT_OF_RESOLUTION].length > 0) { - markerOpts = self._clusters[self.OUT_OF_RESOLUTION].shift(); - self._markerMap[markerOpts.__pgmId]._cluster.isAdded = false; - deleteClusters[markerOpts.__pgmId] = 1; - - if (self._markerMap[markerOpts.__pgmId].__pgmId === activeMarkerId) { - var marker = self._markerMap[markerOpts.__pgmId]._cluster.marker; + var tmpMarkerOpts; + while (self._clusters[self.OUT_OF_RESOLUTION].length > 0) { + tmpMarkerOpts = self._clusters[self.OUT_OF_RESOLUTION].shift(); + self._markerMap[tmpMarkerOpts.__pgmId]._cluster.isAdded = false; + deleteClusters[tmpMarkerOpts.__pgmId] = 1; + + if (self._markerMap[tmpMarkerOpts.__pgmId].__pgmId === activeMarkerId) { + var marker = self._markerMap[tmpMarkerOpts.__pgmId]._cluster.marker; if (marker) { marker.trigger(event.INFO_CLOSE); marker.hideInfoWindow(); } } if (self.debug) { - console.log("---> (js:489)delete:" + markerOpts.__pgmId); + console.log('---> (js:489)delete:' + tmpMarkerOpts.__pgmId); } } keys = Object.keys(self._markerMap); - keys.forEach(function(markerId) { + keys.forEach(function (markerId) { var markerOpts = self._markerMap[markerId]; if (self._isRemoved || - self._stopRequest || - markerOpts._cluster.isRemoved) { + self._stopRequest || + markerOpts._cluster.isRemoved) { return; } @@ -615,61 +638,60 @@ MarkerCluster.prototype._redraw = function(params) { } } else if (resolution === prevResolution) { - //console.log("--->prevResolution(" + prevResolution + ") == resolution(" + resolution + ")"); + //console.log('--->prevResolution(' + prevResolution + ') == resolution(' + resolution + ')'); //-------------------------------------- // Just camera move, no zoom changed //-------------------------------------- keys = Object.keys(self._clusters[prevResolution]); - keys.forEach(function(geocell) { + keys.forEach(function (geocell) { if (self._isRemoved || self._stopRequest) { return; } var cluster = self._clusters[prevResolution][geocell]; var bounds = cluster.getBounds(); - if (!self._isRemoved && !expandedRegion.contains(bounds.northeast) && !expandedRegion.contains(bounds.southwest)) { - ignoreGeocells.push(geocell); + ignoreGeocells.push(geocell); - if (cluster.getMode() === cluster.NO_CLUSTER_MODE) { - cluster.getMarkers().forEach(function(markerOpts, idx) { - deleteClusters[markerOpts.__pgmId] = 1; - self._markerMap[markerOpts.__pgmId]._cluster.isAdded = false; - if (self.debug) { - console.log("---> (js:534)delete:" + markerOpts.__pgmId); - } - if (markerOpts.__pgmId === activeMarkerId) { - var marker = markerOpts._cluster.marker; - if (!marker) { - marker = self._createMarker(markerOpts); - markerOpts._cluster.marker = marker; - } - marker.trigger(event.INFO_CLOSE); - marker.hideInfoWindow(); - } - }); - } else { - deleteClusters[geocell] = 1; + if (cluster.getMode() === cluster.NO_CLUSTER_MODE) { + cluster.getMarkers().forEach(function (markerOpts) { + deleteClusters[markerOpts.__pgmId] = 1; + self._markerMap[markerOpts.__pgmId]._cluster.isAdded = false; if (self.debug) { - console.log("---> (js:549)delete:" + geocell); + console.log('---> (js:534)delete:' + markerOpts.__pgmId); } + if (markerOpts.__pgmId === activeMarkerId) { + var marker = markerOpts._cluster.marker; + if (!marker) { + marker = self._createMarker(markerOpts); + markerOpts._cluster.marker = marker; + } + marker.trigger(event.INFO_CLOSE); + marker.hideInfoWindow(); + } + }); + } else { + deleteClusters[geocell] = 1; + if (self.debug) { + console.log('---> (js:549)delete:' + geocell); } - cluster.remove(); - delete self._clusters[resolution][geocell]; + } + cluster.remove(); + delete self._clusters[resolution][geocell]; } }); keys = Object.keys(self._markerMap); - keys.forEach(function(markerId) { + keys.forEach(function (markerId) { var markerOpts = self._markerMap[markerId]; var geocell = markerOpts._cluster.geocell.substr(0, cellLen); if (self._isRemoved || - self._stopRequest || - markerOpts._cluster.isRemoved || - ignoreGeocells.indexOf(geocell) > -1 || - markerOpts._cluster.isAdded) { + self._stopRequest || + markerOpts._cluster.isRemoved || + ignoreGeocells.indexOf(geocell) > -1 || + markerOpts._cluster.isAdded) { return; } @@ -688,29 +710,29 @@ MarkerCluster.prototype._redraw = function(params) { }); } else if (prevResolution in self._clusters) { - //console.log("--->prevResolution(" + prevResolution + ") != resolution(" + resolution + ")"); + //console.log('--->prevResolution(' + prevResolution + ') != resolution(' + resolution + ')'); if (prevResolution < resolution) { //-------------- // zooming in //-------------- keys = Object.keys(self._clusters[prevResolution]); - keys.forEach(function(geocell) { + keys.forEach(function (geocell) { if (self._isRemoved) { return; } var cluster = self._clusters[prevResolution][geocell]; var noClusterMode = cluster.getMode() === cluster.NO_CLUSTER_MODE; - cluster.getMarkers().forEach(function(markerOpts, idx) { + cluster.getMarkers().forEach(function (markerOpts) { if (self._isRemoved || - self._stopRequest) { + self._stopRequest) { return; } self._markerMap[markerOpts.__pgmId]._cluster.isAdded = false; //targetMarkers.push(markerOpts); if (noClusterMode) { if (self.debug) { - console.log("---> (js:581)delete:" + markerOpts.__pgmId); + console.log('---> (js:581)delete:' + markerOpts.__pgmId); } if (markerOpts.__pgmId === activeMarkerId) { var marker = markerOpts._cluster.marker; @@ -726,7 +748,7 @@ MarkerCluster.prototype._redraw = function(params) { }); if (!noClusterMode) { if (self.debug) { - console.log("---> (js:597)delete:" + geocell); + console.log('---> (js:597)delete:' + geocell); } deleteClusters[geocell] = 1; } @@ -737,18 +759,18 @@ MarkerCluster.prototype._redraw = function(params) { // zooming out //-------------- keys = Object.keys(self._clusters[prevResolution]); - keys.forEach(function(geocell) { + keys.forEach(function (geocell) { if (self._stopRequest || - self._isRemoved) { + self._isRemoved) { return; } var cluster = self._clusters[prevResolution][geocell]; var noClusterMode = cluster.getMode() === cluster.NO_CLUSTER_MODE; - cluster.getMarkers().forEach(function(markerOpts, idx) { + cluster.getMarkers().forEach(function (markerOpts) { self._markerMap[markerOpts.__pgmId]._cluster.isAdded = false; if (noClusterMode) { if (self.debug) { - console.log("---> (js:614)delete:" + markerOpts.__pgmId); + console.log('---> (js:614)delete:' + markerOpts.__pgmId); } if (markerOpts.__pgmId === activeMarkerId) { var marker = markerOpts._cluster.marker; @@ -766,7 +788,7 @@ MarkerCluster.prototype._redraw = function(params) { if (!noClusterMode) { deleteClusters[geocell] = 1; if (self.debug) { - console.log("---> (js:632)delete:" + geocell); + console.log('---> (js:632)delete:' + geocell); } } cluster.remove(); @@ -775,15 +797,15 @@ MarkerCluster.prototype._redraw = function(params) { }); } keys = Object.keys(self._markerMap); - keys.forEach(function(markerId) { + keys.forEach(function (markerId) { if (self._stopRequest || - self._isRemoved) { + self._isRemoved) { return; } var markerOpts = self._markerMap[markerId]; var geocell = markerOpts._cluster.geocell.substr(0, cellLen); if (markerOpts._cluster.isRemoved || - ignoreGeocells.indexOf(geocell) > -1) { + ignoreGeocells.indexOf(geocell) > -1) { self._markerMap[markerOpts.__pgmId]._cluster.isAdded = false; return; } @@ -806,11 +828,11 @@ MarkerCluster.prototype._redraw = function(params) { }); delete self._clusters[prevResolution]; } else { - //console.log("-----> initialize"); + //console.log('-----> initialize'); keys = Object.keys(self._markerMap); - keys.forEach(function(markerId) { + keys.forEach(function (markerId) { if (self._stopRequest || - self._isRemoved) { + self._isRemoved) { return; } var markerOpts = self._markerMap[markerId]; @@ -834,12 +856,12 @@ MarkerCluster.prototype._redraw = function(params) { } if (self._stopRequest || - self._isRemoved) { + self._isRemoved) { self._isWorking = false; return; } if (self.debug) { - console.log("targetMarkers = " + targetMarkers.length); + console.log('targetMarkers = ' + targetMarkers.length); } //-------------------------------- @@ -853,8 +875,8 @@ MarkerCluster.prototype._redraw = function(params) { prevSWcell !== swCell || prevNEcell !== neCell) { - self.set("prevSWcell", swCell); - self.set("prevNEcell", neCell); + self.set('prevSWcell', swCell); + self.set('prevNEcell', neCell); if (resolution !== self.OUT_OF_RESOLUTION) { @@ -862,10 +884,10 @@ MarkerCluster.prototype._redraw = function(params) { // Create clusters //------------------ var prepareClusters = {}; - targetMarkers.forEach(function(markerOpts) { + targetMarkers.forEach(function (markerOpts) { if (markerOpts._cluster.isAdded) { if (self.debug) { - console.log("isAdded", markerOpts); + console.log('isAdded', markerOpts); } return; } @@ -881,7 +903,7 @@ MarkerCluster.prototype._redraw = function(params) { }); if (self.debug) { - console.log("prepareClusters = ", prepareClusters, targetMarkers); + console.log('prepareClusters = ', prepareClusters, targetMarkers); } //------------------------------------------ @@ -890,7 +912,7 @@ MarkerCluster.prototype._redraw = function(params) { keys = Object.keys(prepareClusters); var sortedClusters = []; - keys.forEach(function(geocell) { + keys.forEach(function (geocell) { var cluster = self.getClusterByGeocellAndResolution(geocell, resolution); cluster.addMarkers(prepareClusters[geocell]); @@ -899,7 +921,7 @@ MarkerCluster.prototype._redraw = function(params) { sortedClusters.push(cluster); }); - sortedClusters = sortedClusters.sort(function(a, b) { + sortedClusters = sortedClusters.sort(function (a, b) { return a.geocell.localeCompare(b.geocell); }); @@ -909,16 +931,14 @@ MarkerCluster.prototype._redraw = function(params) { var cluster, anotherCluster, distance; var unionedMarkers = []; i = 0; - var tmp, hit = false; while (i < sortedClusters.length) { cluster = sortedClusters[i]; - hit = false; for (j = i + 1; j < sortedClusters.length; j++) { anotherCluster = sortedClusters[j]; distance = spherical.computeDistanceBetween(cluster._markerCenter, anotherCluster._markerCenter); if (distance < params.clusterDistance) { if (self.debug) { - console.log("---> (js:763)delete:" + anotherCluster.geocell); + console.log('---> (js:763)delete:' + anotherCluster.geocell); } cluster.addMarkers(anotherCluster.getMarkers()); deleteClusters[anotherCluster.getId()] = 1; @@ -926,54 +946,59 @@ MarkerCluster.prototype._redraw = function(params) { self._clusters[resolution][cluster.geocell] = cluster; i = j; } else { - hit = true; break; } } i++; - cluster._markerCnt= cluster.getItemLength(); + cluster._markerCnt = cluster.getItemLength(); unionedMarkers.push(cluster); } - unionedMarkers.forEach(function(cluster) { + unionedMarkers.forEach(function (cluster) { var icon = self.getClusterIcon(cluster), - clusterOpts = { - "count": cluster.getItemLength(), - "position": cluster.getBounds().getCenter(), - "__pgmId": cluster.getId() - }; + clusterOpts = { + 'count': cluster.getItemLength(), + 'position': cluster.getBounds().getCenter(), + '__pgmId': cluster.getId() + }; - if (self.debug) { - clusterOpts.geocell = cluster.geocell; - } + if (self.debug) { + clusterOpts.geocell = cluster.geocell; + } if (icon) { clusterOpts.icon = icon; clusterOpts.isClusterIcon = true; if (cluster.getMode() === cluster.NO_CLUSTER_MODE) { - cluster.getMarkers().forEach(function(markerOpts, idx) { + cluster.getMarkers().forEach(function (markerOpts) { deleteClusters[markerOpts.__pgmId] = 1; if (self.debug) { - console.log("---> (js:800)delete:" + markerOpts.__pgmId); + console.log('---> (js:800)delete:' + markerOpts.__pgmId); } }); } if (self.debug) { - console.log("---> (js:805)add:" + clusterOpts.__pgmId, icon); + console.log('---> (js:805)add:' + clusterOpts.__pgmId, icon); var geocell = clusterOpts.geocell.substr(0, cellLen); var bounds = self._geocellBounds[geocell] || geomodel.computeBox(geocell); self._geocellBounds[geocell] = bounds; self.map.addPolyline({ - color: "blue", + color: 'blue', points: [ bounds.southwest, - {lat: bounds.southwest.lat, lng: bounds.northeast.lng}, + { + lat: bounds.southwest.lat, + lng: bounds.northeast.lng + }, bounds.northeast, - {lat: bounds.northeast.lat, lng: bounds.southwest.lng}, + { + lat: bounds.northeast.lat, + lng: bounds.southwest.lng + }, bounds.southwest ] - }, function(polyline) { + }, function (polyline) { self._clusterBounds.push(polyline); }); } @@ -982,15 +1007,15 @@ MarkerCluster.prototype._redraw = function(params) { return; } - cluster.getMarkers().forEach(function(markerOpts, idx) { + cluster.getMarkers().forEach(function (markerOpts) { if (!markerOpts._cluster.isAdded) { return; } delete deleteClusters[markerOpts.__pgmId]; markerOpts.isClusterIcon = false; if (self.debug) { - console.log("---> (js:831)add:" + markerOpts.__pgmId + ", isAdded = " + markerOpts._cluster.isAdded); - markerOpts.title= markerOpts.__pgmId; + console.log('---> (js:831)add:' + markerOpts.__pgmId + ', isAdded = ' + markerOpts._cluster.isAdded); + markerOpts.title = markerOpts.__pgmId; } new_or_update_clusters.push(markerOpts); }); @@ -998,16 +1023,14 @@ MarkerCluster.prototype._redraw = function(params) { }); } else { cellLen = swCell.length; - var allowGeocell = []; - var ignoreGeocell = []; - targetMarkers.forEach(function(markerOpts) { + targetMarkers.forEach(function (markerOpts) { if (markerOpts._cluster.isAdded) { return; } markerOpts.isClusterIcon = false; if (self.debug) { - console.log("---> (js:859)add:" + markerOpts.__pgmId); - markerOpts.title= markerOpts.__pgmId; + console.log('---> (js:859)add:' + markerOpts.__pgmId); + markerOpts.title = markerOpts.__pgmId; } delete deleteClusters[markerOpts.__pgmId]; self._markerMap[markerOpts.__pgmId]._cluster.isAdded = true; @@ -1019,20 +1042,20 @@ MarkerCluster.prototype._redraw = function(params) { var delete_clusters = Object.keys(deleteClusters); if (self._stopRequest || - new_or_update_clusters.length === 0 && delete_clusters.length === 0) { - self.trigger("nextTask"); + new_or_update_clusters.length === 0 && delete_clusters.length === 0) { + self.trigger('nextTask'); return; } if (self._stopRequest || - self._isRemoved) { + self._isRemoved) { self._isWorking = false; return; } - self.exec.call(self, function(allResults) { + self.exec.call(self, function (allResults) { var markerIDs = Object.keys(allResults); - markerIDs.forEach(function(markerId) { + markerIDs.forEach(function (markerId) { if (!self._markerMap[markerId]) { return; } @@ -1050,38 +1073,40 @@ MarkerCluster.prototype._redraw = function(params) { } self._markerMap[markerId].infoWindowAnchor = self._markerMap[markerId].infoWindowAnchor || [self._markerMap[markerId].icon.size.width / 2, 0]; }); - self.trigger("nextTask"); + self.trigger('nextTask'); }, self.errorHandler, self.getPluginName(), 'redrawClusters', [self.getId(), { - "resolution": resolution, - "new_or_update": new_or_update_clusters, - "delete": delete_clusters - }], {sync: true}); -/* - console.log({ - "resolution": resolution, - "new_or_update": new_or_update_clusters, - "delete": delete_clusters - }); -*/ + 'resolution': resolution, + 'new_or_update': new_or_update_clusters, + 'delete': delete_clusters + }], { + sync: true + }); + /* + console.log({ + 'resolution': resolution, + 'new_or_update': new_or_update_clusters, + 'delete': delete_clusters + }); + */ }; -MarkerCluster.prototype.getClusterIcon = function(cluster) { +MarkerCluster.prototype.getClusterIcon = function (cluster) { var self = this, - hit, - clusterCnt = cluster.getItemLength(); + hit, + clusterCnt = cluster.getItemLength(); for (var i = 0; i < self.icons.length; i++) { hit = false; - if ("min" in self.icons[i]) { + if ('min' in self.icons[i]) { if (clusterCnt >= self.icons[i].min) { - if ("max" in self.icons[i]) { + if ('max' in self.icons[i]) { hit = (clusterCnt <= self.icons[i].max); } else { hit = true; } } } else { - if ("max" in self.icons[i]) { + if ('max' in self.icons[i]) { hit = (clusterCnt <= self.icons[i].max); } } @@ -1092,12 +1117,12 @@ MarkerCluster.prototype.getClusterIcon = function(cluster) { return null; }; -MarkerCluster.prototype._createMarker = function(markerOpts) { +MarkerCluster.prototype._createMarker = function (markerOpts) { var markerId = markerOpts.__pgmId; var self = this; var marker = new Marker(self.getMap(), markerOpts, exec, { - className: "MarkerCluster", - id: self.id + "-" + markerId + className: 'MarkerCluster', + id: self.id + '-' + markerId }); marker._privateInitialize(markerOpts); delete marker._privateInitialize; @@ -1105,25 +1130,25 @@ MarkerCluster.prototype._createMarker = function(markerOpts) { function updateProperty(prevValue, newValue, key) { self._markerMap[markerId][key] = newValue; } - marker.on("title_changed", updateProperty); - marker.on("snippet_changed", updateProperty); - marker.on("animation_changed", updateProperty); - marker.on("infoWindowAnchor_changed", updateProperty); - marker.on("opacity_changed", updateProperty); - marker.on("zIndex_changed", updateProperty); - marker.on("visible_changed", updateProperty); - marker.on("draggable_changed", updateProperty); - marker.on("position_changed", updateProperty); - marker.on("rotation_changed", updateProperty); - marker.on("flat_changed", updateProperty); - marker.on("icon_changed", updateProperty); - marker.one(marker.getId() + "_remove", function() { + marker.on('title_changed', updateProperty); + marker.on('snippet_changed', updateProperty); + marker.on('animation_changed', updateProperty); + marker.on('infoWindowAnchor_changed', updateProperty); + marker.on('opacity_changed', updateProperty); + marker.on('zIndex_changed', updateProperty); + marker.on('visible_changed', updateProperty); + marker.on('draggable_changed', updateProperty); + marker.on('position_changed', updateProperty); + marker.on('rotation_changed', updateProperty); + marker.on('flat_changed', updateProperty); + marker.on('icon_changed', updateProperty); + marker.one(marker.getId() + '_remove', function () { self.removeMarkerById(markerId); }); return marker; }; -MarkerCluster.prototype.getClusterByGeocellAndResolution = function(geocell, resolution) { +MarkerCluster.prototype.getClusterByGeocellAndResolution = function (geocell, resolution) { var self = this; geocell = geocell.substr(0, resolution + 1); diff --git a/www/Overlay.js b/www/Overlay.js index bee872dd6..56d3012a6 100644 --- a/www/Overlay.js +++ b/www/Overlay.js @@ -1,12 +1,11 @@ var BaseClass = require('./BaseClass'), - utils = require('cordova/utils'), - BaseArrayClass = require('./BaseArrayClass'); - + utils = require('cordova/utils'), + BaseArrayClass = require('./BaseArrayClass'); /***************************************************************************** * Overlay Class *****************************************************************************/ -var Overlay = function(map, options, className, _exec, extras) { +var Overlay = function (map, options, className, _exec, extras) { extras = extras || {}; BaseClass.apply(this); @@ -15,14 +14,14 @@ var Overlay = function(map, options, className, _exec, extras) { //----------------------------------------------- // Sets the initialize option to each property //----------------------------------------------- - var ignores = ["map", "id", "hashCode", "type"]; + var ignores = ['map', 'id', 'hashCode', 'type']; if (extras.ignores) { ignores = ignores.concat(extras.ignores); } for (var key in options) { - if (ignores.indexOf(key) === -1) { - self.set(key, options[key]); - } + if (ignores.indexOf(key) === -1) { + self.set(key, options[key]); + } } //------------------------------------------------------------------------------- @@ -31,60 +30,59 @@ var Overlay = function(map, options, className, _exec, extras) { // If this overlay is ready, execute it. //------------------------------------------------------------------------------- var cmdQueue = new BaseArrayClass(); - cmdQueue.on('insert_at', function() { + cmdQueue.on('insert_at', function () { if (!self._isReady) { return; } var cmd; - while(cmdQueue.getLength() > 0) { + while (cmdQueue.getLength() > 0) { cmd = cmdQueue.removeAt(0, true); - if (cmd && cmd.target && cmd.args && cmd.args[0] !== "nop") { + if (cmd && cmd.target && cmd.args && cmd.args[0] !== 'nop') { _exec.apply(cmd.target, cmd.args); } } }); - - Object.defineProperty(self, "_cmdQueue", { + Object.defineProperty(self, '_cmdQueue', { enumerable: false, value: cmdQueue, writable: false }); - Object.defineProperty(self, "_isReady", { + Object.defineProperty(self, '_isReady', { value: false, writable: true }); - Object.defineProperty(self, "map", { + Object.defineProperty(self, 'map', { value: map, writable: false }); - Object.defineProperty(self, "id", { - value: extras.id || (className.toLowerCase()) + "_" + this.hashCode, + Object.defineProperty(self, 'id', { + value: extras.id || (className.toLowerCase()) + '_' + this.hashCode, writable: false }); - Object.defineProperty(self, "type", { + Object.defineProperty(self, 'type', { value: className, writable: false }); - Object.defineProperty(self, "getPluginName", { + Object.defineProperty(self, 'getPluginName', { writable: false, - value: function() { - return this.map.getId() + "-" + className.toLowerCase(); + value: function () { + return this.map.getId() + '-' + className.toLowerCase(); } }); }; utils.extend(Overlay, BaseClass); -Overlay.prototype._privateInitialize = function(options) { +Overlay.prototype._privateInitialize = function (options) { var self = this; //----------------------------------------------- // Sets the initialize option to each property //----------------------------------------------- if (options) { - var ignores = ["map", "id", "hashCode", "type"]; + var ignores = ['map', 'id', 'hashCode', 'type']; for (var key in options) { if (ignores.indexOf(key) === -1) { self.set(key, options[key], true); @@ -95,27 +93,26 @@ Overlay.prototype._privateInitialize = function(options) { //----------------------------------------------- // Trigger internal command queue //----------------------------------------------- - Object.defineProperty(self, "_isReady", { + Object.defineProperty(self, '_isReady', { value: true, writable: false }); - self.exec("nop"); + self.exec('nop'); }; - -Overlay.prototype.exec = function() { +Overlay.prototype.exec = function () { this._cmdQueue.push.call(this._cmdQueue, { target: this, args: Array.prototype.slice.call(arguments, 0) }); }; -Overlay.prototype.getId = function() { +Overlay.prototype.getId = function () { return this.id; }; -Overlay.prototype.getMap = function() { +Overlay.prototype.getMap = function () { return this.map; }; -Overlay.prototype.getHashCode = function() { +Overlay.prototype.getHashCode = function () { return this.hashCode; }; diff --git a/www/Polygon.js b/www/Polygon.js index 94230d779..457a3d6fa 100644 --- a/www/Polygon.js +++ b/www/Polygon.js @@ -1,8 +1,6 @@ -var argscheck = require('cordova/argscheck'), - utils = require('cordova/utils'), +var utils = require('cordova/utils'), common = require('./Common'), - Overlay = require('./Overlay'), - BaseArrayClass = require('./BaseArrayClass'); + Overlay = require('./Overlay'); /***************************************************************************** * Polygon Class @@ -29,7 +27,7 @@ var Polygon = function (map, polygonOptions, _exec) { self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'removePointAt', [polygonId, index]); }); - Object.defineProperty(self, "points", { + Object.defineProperty(self, 'points', { value: pointsProperty, writable: false }); @@ -66,7 +64,7 @@ var Polygon = function (map, polygonOptions, _exec) { self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'insertHoleAt', [polygonId, index, array.getArray()]); }); - Object.defineProperty(self, "holes", { + Object.defineProperty(self, 'holes', { value: holesProperty, writable: false }); @@ -74,7 +72,7 @@ var Polygon = function (map, polygonOptions, _exec) { //-------------------------- // other properties //--------------------------. - // var ignores = ["map", "id", "hashCode", "type", "points", "holes"]; + // var ignores = ['map', 'id', 'hashCode', 'type', 'points', 'holes']; // for (var key in polygonOptions) { // if (ignores.indexOf(key) === -1) { // self.set(key, polygonOptions[key]); @@ -83,32 +81,32 @@ var Polygon = function (map, polygonOptions, _exec) { //----------------------------------------------- // Sets event listeners //----------------------------------------------- - self.on("clickable_changed", function () { - var clickable = self.get("clickable"); + self.on('clickable_changed', function () { + var clickable = self.get('clickable'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setClickable', [self.getId(), clickable]); }); - self.on("geodesic_changed", function () { - var geodesic = self.get("geodesic"); + self.on('geodesic_changed', function () { + var geodesic = self.get('geodesic'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setGeodesic', [self.getId(), geodesic]); }); - self.on("zIndex_changed", function () { - var zIndex = self.get("zIndex"); + self.on('zIndex_changed', function () { + var zIndex = self.get('zIndex'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setZIndex', [self.getId(), zIndex]); }); - self.on("visible_changed", function () { - var visible = self.get("visible"); + self.on('visible_changed', function () { + var visible = self.get('visible'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setVisible', [self.getId(), visible]); }); - self.on("strokeWidth_changed", function () { - var width = self.get("strokeWidth"); + self.on('strokeWidth_changed', function () { + var width = self.get('strokeWidth'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setStrokeWidth', [self.getId(), width]); }); - self.on("strokeColor_changed", function () { - var color = self.get("strokeColor"); + self.on('strokeColor_changed', function () { + var color = self.get('strokeColor'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setStrokeColor', [self.getId(), common.HTMLColor2RGBA(color, 0.75)]); }); - self.on("fillColor_changed", function () { - var color = self.get("fillColor"); + self.on('fillColor_changed', function () { + var color = self.get('fillColor'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setFillColor', [self.getId(), common.HTMLColor2RGBA(color, 0.75)]); }); @@ -119,17 +117,17 @@ utils.extend(Polygon, Overlay); Polygon.prototype.remove = function (callback) { var self = this; if (self._isRemoved) { - if (typeof callback === "function") { + if (typeof callback === 'function') { return; } else { return Promise.resolve(); } } - Object.defineProperty(self, "_isRemoved", { + Object.defineProperty(self, '_isRemoved', { value: true, writable: false }); - self.trigger(this.id + "_remove"); + self.trigger(this.id + '_remove'); var resolver = function(resolve, reject) { self.exec.call(self, @@ -143,7 +141,7 @@ Polygon.prototype.remove = function (callback) { }); }; - if (typeof callback === "function") { + if (typeof callback === 'function') { resolver(callback, self.errorHandler); } else { return new Promise(resolver); @@ -156,8 +154,7 @@ Polygon.prototype.setPoints = function (points) { var mvcArray = self.points; mvcArray.empty(true); - var i, - path = []; + var i; for (i = 0; i < points.length; i++) { mvcArray.push(common.getLatLng(points[i]), true); diff --git a/www/Polyline.js b/www/Polyline.js index 0c25eb618..886da3bc0 100644 --- a/www/Polyline.js +++ b/www/Polyline.js @@ -1,15 +1,13 @@ -var argscheck = require('cordova/argscheck'), - utils = require('cordova/utils'), +var utils = require('cordova/utils'), common = require('./Common'), - Overlay = require('./Overlay'), - BaseArrayClass = require('./BaseArrayClass'); + Overlay = require('./Overlay'); /***************************************************************************** * Polyline Class *****************************************************************************/ var Polyline = function (map, polylineOptions, _exec) { Overlay.call(this, map, polylineOptions, 'Polyline', _exec, { - "ignores": ["points"] + 'ignores': ['points'] }); var self = this; @@ -31,14 +29,14 @@ var Polyline = function (map, polylineOptions, _exec) { self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'removePointAt', [polylineId, index]); }); - Object.defineProperty(self, "points", { + Object.defineProperty(self, 'points', { value: pointsProperty, writable: false }); //----------------------------------------------- // Sets the initialize option to each property //----------------------------------------------- - // var ignores = ["map", "id", "hashCode", "type", "points"]; + // var ignores = ['map', 'id', 'hashCode', 'type', 'points']; // for (var key in polylineOptions) { // if (ignores.indexOf(key) === -1) { // self.set(key, polylineOptions[key]); @@ -48,34 +46,34 @@ var Polyline = function (map, polylineOptions, _exec) { //----------------------------------------------- // Sets event listeners //----------------------------------------------- - self.on("geodesic_changed", function () { + self.on('geodesic_changed', function () { if (self._isRemoved) return; - var geodesic = self.get("geodesic"); + var geodesic = self.get('geodesic'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setGeodesic', [self.getId(), geodesic]); }); - self.on("zIndex_changed", function () { + self.on('zIndex_changed', function () { if (self._isRemoved) return; - var zIndex = self.get("zIndex"); + var zIndex = self.get('zIndex'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setZIndex', [self.getId(), zIndex]); }); - self.on("clickable_changed", function () { + self.on('clickable_changed', function () { if (self._isRemoved) return; - var clickable = self.get("clickable"); + var clickable = self.get('clickable'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setClickable', [self.getId(), clickable]); }); - self.on("visible_changed", function () { + self.on('visible_changed', function () { if (self._isRemoved) return; - var visible = self.get("visible"); + var visible = self.get('visible'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setVisible', [self.getId(), visible]); }); - self.on("strokeWidth_changed", function () { + self.on('strokeWidth_changed', function () { if (self._isRemoved) return; - var strokeWidth = self.get("strokeWidth"); + var strokeWidth = self.get('strokeWidth'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setStrokeWidth', [self.getId(), strokeWidth]); }); - self.on("strokeColor_changed", function () { + self.on('strokeColor_changed', function () { if (self._isRemoved) return; - var color = self.get("strokeColor"); + var color = self.get('strokeColor'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setStrokeColor', [self.getId(), common.HTMLColor2RGBA(color, 0.75)]); }); @@ -88,13 +86,12 @@ Polyline.prototype.setPoints = function (points) { var mvcArray = self.points; mvcArray.empty(true); - var i, - path = []; + var i; for (i = 0; i < points.length; i++) { mvcArray.push({ - "lat": points[i].lat, - "lng": points[i].lng + 'lat': points[i].lat, + 'lng': points[i].lng }, true); } self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setPoints', [self.id, mvcArray.getArray()]); @@ -149,23 +146,23 @@ Polyline.prototype.getZIndex = function () { return this.get('zIndex'); }; -Polyline.prototype.remove = function () { +Polyline.prototype.remove = function (callback) { var self = this; if (self._isRemoved) { - if (typeof callback === "function") { + if (typeof callback === 'function') { return; } else { return Promise.resolve(); } } - Object.defineProperty(self, "_isRemoved", { + Object.defineProperty(self, '_isRemoved', { value: true, writable: false }); - var resolver = function(resolve, reject) { + var resolver = function (resolve, reject) { self.exec.call(self, - function() { + function () { self.destroy(); resolve.call(self); }, @@ -176,7 +173,7 @@ Polyline.prototype.remove = function () { }; var result; - if (typeof callback === "function") { + if (typeof callback === 'function') { resolver(callback, self.errorHandler); } else { result = new Promise(resolver); @@ -185,7 +182,7 @@ Polyline.prototype.remove = function () { if (self.points) { self.points.empty(); } - self.trigger(self.id + "_remove"); + self.trigger(self.id + '_remove'); return result; }; diff --git a/www/StreetViewPanorama.js b/www/StreetViewPanorama.js index a5569b7b6..8f38548de 100644 --- a/www/StreetViewPanorama.js +++ b/www/StreetViewPanorama.js @@ -1,5 +1,4 @@ -var argscheck = require('cordova/argscheck'), - utils = require('cordova/utils'), +var utils = require('cordova/utils'), common = require('./Common'), event = require('./event'), Overlay = require('./Overlay'); @@ -15,36 +14,36 @@ var StreetViewPanorama = function(streetViewId, _exec) { }); var self = this; - self.set("visible", true); - self.set("gesture_panning", true); - self.set("gesture_zoom", true); - self.set("control_navigation", true); - self.set("control_streetNames", true); - self.set("camera_zoom", 0); - self.set("camera_tilt", 0); - self.set("camera_bearing", 0); + self.set('visible', true); + self.set('gesture_panning', true); + self.set('gesture_zoom', true); + self.set('control_navigation', true); + self.set('control_streetNames', true); + self.set('camera_zoom', 0); + self.set('camera_tilt', 0); + self.set('camera_bearing', 0); //----------------------------------------------- // Sets event listeners //----------------------------------------------- - self.on("gesture_panning_changed", function() { - var booleanValue = self.get("gesture_panning"); + self.on('gesture_panning_changed', function() { + var booleanValue = self.get('gesture_panning'); self.exec.call(self, null, self.errorHandler, self.id, 'setPanningGesturesEnabled', [booleanValue]); }); - self.on("gesture_zoom_changed", function() { - var booleanValue = self.get("gesture_zoom"); + self.on('gesture_zoom_changed', function() { + var booleanValue = self.get('gesture_zoom'); self.exec.call(self, null, self.errorHandler, self.id, 'setZoomGesturesEnabled', [booleanValue]); }); - self.on("control_navigation_changed", function() { - var booleanValue = self.get("control_navigation"); + self.on('control_navigation_changed', function() { + var booleanValue = self.get('control_navigation'); self.exec.call(self, null, self.errorHandler, self.id, 'setNavigationEnabled', [booleanValue]); }); - self.on("control_streetNames_changed", function() { - var booleanValue = self.get("control_streetNames"); + self.on('control_streetNames_changed', function() { + var booleanValue = self.get('control_streetNames'); self.exec.call(self, null, self.errorHandler, self.id, 'setStreetNamesEnabled', [booleanValue]); }); - self.on("visible_changed", function() { - var booleanValue = self.get("visible"); + self.on('visible_changed', function() { + var booleanValue = self.get('visible'); self.exec.call(self, null, self.errorHandler, self.id, 'setVisible', [booleanValue]); }); }; @@ -53,7 +52,7 @@ var StreetViewPanorama = function(streetViewId, _exec) { utils.extend(StreetViewPanorama, Overlay); StreetViewPanorama.prototype.getPluginName = function() { - return this.map.getId() + "-streetview"; + return this.map.getId() + '-streetview'; }; StreetViewPanorama.prototype.getHashCode = function() { @@ -69,24 +68,24 @@ StreetViewPanorama.prototype.getPanorama = function(meta, panorama, div, options options = options || {}; - //self.set("clickable", options.clickable === false ? false : true); - self.set("visible", options.visible === false ? false : true, true); + //self.set('clickable', options.clickable === false ? false : true); + self.set('visible', options.visible === false ? false : true, true); args.push(options); // Initial camera options - if ("camera" in options) { - self.set("camera", options.camera, true); - if ("zoom" in options.camera) { - self.set("camera_zoom", options.camera.zoom, true); + if ('camera' in options) { + self.set('camera', options.camera, true); + if ('zoom' in options.camera) { + self.set('camera_zoom', options.camera.zoom, true); } - if ("bearing" in options.camera) { - self.set("camera_bearing", options.camera.bearing, true); + if ('bearing' in options.camera) { + self.set('camera_bearing', options.camera.bearing, true); } - if ("tilt" in options.camera) { - self.set("camera_tilt", options.camera.tilt, true); + if ('tilt' in options.camera) { + self.set('camera_tilt', options.camera.tilt, true); } - if ("target" in options.camera) { - self.set("position", options.camera.target, true); + if ('target' in options.camera) { + self.set('position', options.camera.target, true); } } @@ -94,20 +93,20 @@ StreetViewPanorama.prototype.getPanorama = function(meta, panorama, div, options options.gestures = options.gestures || {}; options.gestures.panning = common.defaultTrueOption(options.gestures.panning); options.gestures.zoom = common.defaultTrueOption(options.gestures.zoom); - self.set("gesture_panning", options.gestures.panning, true); - self.set("gesture_zoom", options.gestures.zoom, true); + self.set('gesture_panning', options.gestures.panning, true); + self.set('gesture_zoom', options.gestures.zoom, true); // Controls options options.controls = options.controls || {}; options.controls.navigation = common.defaultTrueOption(options.controls.navigation); options.controls.streetNames = common.defaultTrueOption(options.controls.streetNames); - self.set("control_navigation", options.controls.navigation, true); - self.set("control_streetNames", options.controls.streetNames, true); + self.set('control_navigation', options.controls.navigation, true); + self.set('control_streetNames', options.controls.streetNames, true); // Gets the map div size. // The plugin needs to consider the viewport zoom ratio // for the case window.innerHTML > body.offsetWidth. - self.set("div", div); + self.set('div', div); var elemId = common.getPluginDomId(div); args.push(elemId); @@ -120,9 +119,9 @@ StreetViewPanorama.prototype.getPanorama = function(meta, panorama, div, options //------------------------------------------------------------------------ var positionCSS; for (var i = 0; i < div.children.length; i++) { - positionCSS = common.getStyle(div.children[i], "position"); - if (positionCSS === "static") { - div.children[i].style.position = "relative"; + positionCSS = common.getStyle(div.children[i], 'position'); + if (positionCSS === 'static') { + div.children[i].style.position = 'relative'; } } //div.insertBefore(self._layers.info, div.firstChild); @@ -140,7 +139,7 @@ StreetViewPanorama.prototype.getPanorama = function(meta, panorama, div, options div = div.parentNode; } - cordova.fireDocumentEvent("plugin_touch", { + cordova.fireDocumentEvent('plugin_touch', { force: true }); self._privateInitialize(); @@ -153,16 +152,16 @@ StreetViewPanorama.prototype.getPanorama = function(meta, panorama, div, options }; StreetViewPanorama.prototype.setVisible = function(isVisible) { - this.set("visible", common.parseBoolean(isVisible)); + this.set('visible', common.parseBoolean(isVisible)); return this; }; StreetViewPanorama.prototype.getVisible = function() { - return this.get("visible"); + return this.get('visible'); }; StreetViewPanorama.prototype.getDiv = function() { - return this.get("div"); + return this.get('div'); }; StreetViewPanorama.prototype.getMap = function() { // stub @@ -216,20 +215,20 @@ StreetViewPanorama.prototype.getPosition = function () { StreetViewPanorama.prototype.setPosition = function(cameraPosition, callback) { var self = this; cameraPosition = cameraPosition || {}; - if (typeof cameraPosition === "string") { + if (typeof cameraPosition === 'string') { // case: panorama.setPosition(panoId); cameraPosition = { target : cameraPosition }; } - if (typeof cameraPosition.target === "object") { + if (typeof cameraPosition.target === 'object') { // case: panorama.setPosition({ // target: {lat: ..., lng: ...} // }); - self.set("position", cameraPosition.target); + self.set('position', cameraPosition.target); } self.exec.call(self, function() { - if (typeof callback === "function") { + if (typeof callback === 'function') { callback.call(self); } }, self.errorHandler, self.id, 'setPosition', [cameraPosition], { @@ -241,17 +240,17 @@ StreetViewPanorama.prototype.setPosition = function(cameraPosition, callback) { StreetViewPanorama.prototype.setPov = function(pov, callback) { var self = this; pov = pov || {}; - if ("zoom" in pov) { - self.set("camera_zoom", pov.zoom); + if ('zoom' in pov) { + self.set('camera_zoom', pov.zoom); } - if ("bearing" in pov) { - self.set("camera_bearing", pov.bearing); + if ('bearing' in pov) { + self.set('camera_bearing', pov.bearing); } - if ("tilt" in pov) { - self.set("camera_tilt", pov.tilt); + if ('tilt' in pov) { + self.set('camera_tilt', pov.tilt); } self.exec.call(self, function() { - if (typeof callback === "function") { + if (typeof callback === 'function') { callback.call(self); } }, self.errorHandler, self.id, 'setPov', [pov], { @@ -277,7 +276,7 @@ StreetViewPanorama.prototype.remove = function(callback) { }); }; - if (typeof callback === "function") { + if (typeof callback === 'function') { resolver(callback, self.errorHandler); } else { return new Promise(resolver); @@ -290,11 +289,11 @@ StreetViewPanorama.prototype.remove = function(callback) { - self.trigger("remove"); + self.trigger('remove'); }; StreetViewPanorama.prototype._onPanoramaCameraChange = function(eventName, cameraPosition) { var self = this; - self.set('camera', utils.clone(self.get("camera") || {}, cameraPosition)); + self.set('camera', utils.clone(self.get('camera') || {}, cameraPosition)); self.set('camera_zoom', cameraPosition.zoom); self.set('camera_bearing', cameraPosition.bearing); self.set('camera_tilt', cameraPosition.viewAngle || cameraPosition.tilt); @@ -313,7 +312,7 @@ StreetViewPanorama.prototype._onPanoramaLocationChange = function(eventName, pan self._onPanoramaEvent(eventName, panoramaLocation); } }; -StreetViewPanorama.prototype._onPanoramaEvent = function(eventName) { +StreetViewPanorama.prototype._onPanoramaEvent = function() { var self = this; if (self._isReady) { var args = Array.prototype.slice.call(arguments, 0); diff --git a/www/Thread.js b/www/Thread.js index f6bdfbc13..278023fa3 100644 --- a/www/Thread.js +++ b/www/Thread.js @@ -9,38 +9,38 @@ // // 1. Definitions. // -// "License" shall mean the terms and conditions for use, reproduction, +// '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 +// '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 +// '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 +// '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 +// '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, +// '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 +// '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 +// '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 +// '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 @@ -48,21 +48,21 @@ // 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 +// '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" +// 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." +// designated in writing by the copyright owner as 'Not a Contribution.' // -// "Contributor" shall mean Licensor and any individual or Legal Entity +// '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. // @@ -106,7 +106,7 @@ // 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 +// (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 @@ -145,7 +145,7 @@ // // 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, +// 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 @@ -181,24 +181,24 @@ // 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 "{}" +// 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 +// same 'printed page' as the copyright notice for easier // identification within third-party archives. // // Copyright 2017 deep-rain.com // -// Licensed under the Apache License, Version 2.0 (the "License"); +// 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, +// 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. @@ -206,179 +206,176 @@ // Constants var Type = { - RESOLVE: "resolve", - NOTIFY: "notify" + RESOLVE: 'resolve', + NOTIFY: 'notify' }; -var REPLACE_SEQUENCE = "{{#CODE}}"; +var REPLACE_SEQUENCE = '{{#CODE}}'; var CODE = 'onmessage = function(e){ postMessage({type:"' + Type.RESOLVE + '",content:({{#CODE}}).call(this, (e.data ? JSON.parse(e.data) : undefined))});};function notify(c){postMessage({type:"' + Type.NOTIFY + '", content:c})}'; -var getEmbeddedCode = function(s) { - return CODE.replace(REPLACE_SEQUENCE, s); +var getEmbeddedCode = function (s) { + return CODE.replace(REPLACE_SEQUENCE, s); }; -module.exports = (function() { +module.exports = (function () { - // Deferred class - var Deferred = function() { - this.resolveQueues = []; - this.rejectQueues = []; - this.progressQueues = []; - this.args = null; - this.isDone = false; - this.isFailed = false; - }; + // Deferred class + var Deferred = function () { + this.resolveQueues = []; + this.rejectQueues = []; + this.progressQueues = []; + this.args = null; + this.isDone = false; + this.isFailed = false; + }; - Deferred.prototype.done = function(func) { - if (this.isDone) { - func(this.args); - } - else { - this.resolveQueues.push(func); - } - return this; - }; + Deferred.prototype.done = function (func) { + if (this.isDone) { + func(this.args); + } else { + this.resolveQueues.push(func); + } + return this; + }; - Deferred.prototype.fail = function(func) { - if (this.isFailed) { - func(this.args); - } - else { - this.rejectQueues.push(func); - } - return this; - }; + Deferred.prototype.fail = function (func) { + if (this.isFailed) { + func(this.args); + } else { + this.rejectQueues.push(func); + } + return this; + }; - Deferred.prototype.always = function(func) { - if (this.isFailed || this.isDone) { - func(this.args); - } - else { - this.resolveQueues.push(func); - this.rejectQueues.push(func); - } - return this; - }; + Deferred.prototype.always = function (func) { + if (this.isFailed || this.isDone) { + func(this.args); + } else { + this.resolveQueues.push(func); + this.rejectQueues.push(func); + } + return this; + }; - Deferred.prototype.progress = function(func) { - this.progressQueues.push(func); - }; + Deferred.prototype.progress = function (func) { + this.progressQueues.push(func); + }; - Deferred.prototype.resolve = function(obj) { - this.isDone = true; - this.args = obj; - this.resolveQueues.forEach(function(q) { - q(obj); - }); - return this; - }; + Deferred.prototype.resolve = function (obj) { + this.isDone = true; + this.args = obj; + this.resolveQueues.forEach(function (q) { + q(obj); + }); + return this; + }; - Deferred.prototype.notify = function(obj) { - this.progressQueues.forEach(function(q) { - q(obj); - }); - }; + Deferred.prototype.notify = function (obj) { + this.progressQueues.forEach(function (q) { + q(obj); + }); + }; - Deferred.prototype.reject = function(obj) { - this.isFailed = true; - this.args = obj; - this.rejectQueues.forEach(function(q) { - q(obj); - }); - return this; - }; + Deferred.prototype.reject = function (obj) { + this.isFailed = true; + this.args = obj; + this.rejectQueues.forEach(function (q) { + q(obj); + }); + return this; + }; - // Thread class - var Thread = function(func, depends) { + // Thread class + var Thread = function (func, depends) { - // check browser - if (!window.Blob || - !window.URL || - !window.Worker) { - throw new Error("this browser is not supported"); - } + // check browser + if (!window.Blob || + !window.URL || + !window.Worker) { + throw new Error('this browser is not supported'); + } - // inject dependent libraries. - depends = depends || []; - if (!(depends instanceof window.Array)) { - depends = [depends]; - } + // inject dependent libraries. + depends = depends || []; + if (!(depends instanceof window.Array)) { + depends = [depends]; + } - var scripts = ""; - if (depends.length > 0) { - scripts = 'importScripts("' + depends.join('","') + '");'; - } + var scripts = ''; + if (depends.length > 0) { + scripts = 'importScripts("' + depends.join('','') + '");'; + } - // create Blob object. - var blob = new window.Blob([scripts + getEmbeddedCode(func.toString())]); - this.blobUrl = window.URL.createObjectURL(blob); + // create Blob object. + var blob = new window.Blob([scripts + getEmbeddedCode(func.toString())]); + this.blobUrl = window.URL.createObjectURL(blob); - // greate Worker object. - this.worker = new window.Worker(this.blobUrl); - this.deferred = new Deferred(); + // greate Worker object. + this.worker = new window.Worker(this.blobUrl); + this.deferred = new Deferred(); - // add event listener. - var self = this; + // add event listener. + var self = this; - // onmessage - this.worker.addEventListener("message", function(e) { - switch (e.data.type) { - case Type.RESOLVE: - self.deferred.resolve(e.data.content); - return; - case Type.NOTIFY: - self.deferred.notify(e.data.content); - return; - } - }); + // onmessage + this.worker.addEventListener('message', function (e) { + switch (e.data.type) { + case Type.RESOLVE: + self.deferred.resolve(e.data.content); + return; + case Type.NOTIFY: + self.deferred.notify(e.data.content); + return; + } + }); - // onerror - this.worker.addEventListener("error", function(e) { - self.deferred.reject(e); - }); - }; + // onerror + this.worker.addEventListener('error', function (e) { + self.deferred.reject(e); + }); + }; - Thread.prototype.execute = function(obj) { - if (this.isClosed) { - throw new Error("thread has been closed."); - } + Thread.prototype.execute = function (obj) { + if (this.isClosed) { + throw new Error('thread has been closed.'); + } - var json = JSON.stringify(obj); - this.worker.postMessage(json); - return this; - }; + var json = JSON.stringify(obj); + this.worker.postMessage(json); + return this; + }; - Thread.prototype.once = function(args) { - var self = this; - this.deferred.always(function() { - self.terminate(); - }); - this.execute(args); - this.isClosed = true; - return this; - }; + Thread.prototype.once = function (args) { + var self = this; + this.deferred.always(function () { + self.terminate(); + }); + this.execute(args); + this.isClosed = true; + return this; + }; - Thread.prototype.terminate = function() { - window.URL.revokeObjectURL(this.blobUrl); - this.worker.terminate(); - this.worker = null; - this.deferred = null; - this.blobUrl = null; - }; + Thread.prototype.terminate = function () { + window.URL.revokeObjectURL(this.blobUrl); + this.worker.terminate(); + this.worker = null; + this.deferred = null; + this.blobUrl = null; + }; - Thread.prototype.done = function(f) { - this.deferred.done(f); - return this; - }; + Thread.prototype.done = function (f) { + this.deferred.done(f); + return this; + }; - Thread.prototype.fail = function(f) { - this.deferred.fail(f); - return this; - }; + Thread.prototype.fail = function (f) { + this.deferred.fail(f); + return this; + }; - Thread.prototype.progress = function(f) { - this.deferred.progress(f); - return this; - }; + Thread.prototype.progress = function (f) { + this.deferred.progress(f); + return this; + }; - return Thread; + return Thread; })(); diff --git a/www/TileOverlay.js b/www/TileOverlay.js index dfa184a40..6f38b20ee 100644 --- a/www/TileOverlay.js +++ b/www/TileOverlay.js @@ -1,5 +1,4 @@ -var argscheck = require('cordova/argscheck'), - utils = require('cordova/utils'), +var utils = require('cordova/utils'), common = require('./Common'), Overlay = require('./Overlay'); @@ -14,20 +13,20 @@ var TileOverlay = function (map, tileOverlayOptions, _exec) { //----------------------------------------------- // Sets event listeners //----------------------------------------------- - self.on("fadeIn_changed", function () { - var fadeIn = self.get("fadeIn"); + self.on('fadeIn_changed', function () { + var fadeIn = self.get('fadeIn'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setFadeIn', [self.getId(), fadeIn]); }); - self.on("opacity_changed", function () { - var opacity = self.get("opacity"); + self.on('opacity_changed', function () { + var opacity = self.get('opacity'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setOpacity', [self.getId(), opacity]); }); - self.on("zIndex_changed", function () { - var zIndex = self.get("zIndex"); + self.on('zIndex_changed', function () { + var zIndex = self.get('zIndex'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setZIndex', [self.getId(), zIndex]); }); - self.on("visible_changed", function () { - var visible = self.get("visible"); + self.on('visible_changed', function () { + var visible = self.get('visible'); self.exec.call(self, null, self.errorHandler, self.getPluginName(), 'setVisible', [self.getId(), visible]); }); }; @@ -35,7 +34,7 @@ var TileOverlay = function (map, tileOverlayOptions, _exec) { utils.extend(TileOverlay, Overlay); TileOverlay.prototype.getPluginName = function () { - return this.map.getId() + "-tileoverlay"; + return this.map.getId() + '-tileoverlay'; }; TileOverlay.prototype.getHashCode = function () { @@ -49,10 +48,10 @@ TileOverlay.prototype.getId = function () { return this.id; }; TileOverlay.prototype.getTileSize = function () { - return this.get("tileSize"); + return this.get('tileSize'); }; TileOverlay.prototype.getZIndex = function () { - return this.get("zIndex"); + return this.get('zIndex'); }; TileOverlay.prototype.setZIndex = function (zIndex) { this.set('zIndex', zIndex); @@ -85,17 +84,17 @@ TileOverlay.prototype.getVisible = function () { TileOverlay.prototype.remove = function (callback) { var self = this; if (self._isRemoved) { - if (typeof callback === "function") { + if (typeof callback === 'function') { return; } else { return Promise.resolve(); } } - Object.defineProperty(self, "_isRemoved", { + Object.defineProperty(self, '_isRemoved', { value: true, writable: false }); - self.trigger(self.id + "_remove"); + self.trigger(self.id + '_remove'); var resolver = function(resolve, reject) { self.exec.call(self, @@ -109,7 +108,7 @@ TileOverlay.prototype.remove = function (callback) { }); }; - if (typeof callback === "function") { + if (typeof callback === 'function') { resolver(callback, self.errorHandler); } else { return new Promise(resolver); diff --git a/www/VisibleRegion.js b/www/VisibleRegion.js index 73c0a04ab..d04c9a265 100644 --- a/www/VisibleRegion.js +++ b/www/VisibleRegion.js @@ -1,14 +1,13 @@ var utils = require('cordova/utils'), - LatLngBounds = require('./LatLngBounds'), - LatLng = require('./LatLng'); + LatLngBounds = require('./LatLngBounds'); /***************************************************************************** * VisibleRegion Class *****************************************************************************/ var VisibleRegion = function(southwest, northeast, farLeft, farRight, nearLeft, nearRight) { - Object.defineProperty(this, "type", { - value: "VisibleRegion", - writable: false + Object.defineProperty(this, 'type', { + value: 'VisibleRegion', + writable: false }); this.southwest = southwest; this.northeast = northeast; @@ -24,44 +23,44 @@ delete VisibleRegion.prototype.extend; delete VisibleRegion.prototype.getCenter; VisibleRegion.prototype.contains = function(latLng) { - if (!latLng || !("lat" in latLng) || !("lng" in latLng)) { - return false; - } - var y = latLng.lat, - x = latLng.lng; + if (!latLng || !('lat' in latLng) || !('lng' in latLng)) { + return false; + } + var y = latLng.lat, + x = latLng.lng; - var y90 = y + 90; - var south = this.southwest.lat, - north = this.northeast.lat, - west = this.southwest.lng, - east = this.northeast.lng; - var south90 = south + 90, - north90 = north + 90; + var y90 = y + 90; + var south = this.southwest.lat, + north = this.northeast.lat, + west = this.southwest.lng, + east = this.northeast.lng; + var south90 = south + 90, + north90 = north + 90; - var containX = false, - containY = false; + var containX = false, + containY = false; - if (east >= 0 && west >= east) { - if (x <= 0 && x >= -180) { - containX = true; - } else { - containX = (west <= x && x <= east); - } - } else if (west <= 0 && east <= west) { + if (east >= 0 && west >= east) { + if (x <= 0 && x >= -180) { + containX = true; + } else { containX = (west <= x && x <= east); - if (x >= 0 && x <= 180) { - containX = true; - } else { - containX = (x <= 0 && x <= west || x <= east && x>= -180); - } + } + } else if (west <= 0 && east <= west) { + containX = (west <= x && x <= east); + if (x >= 0 && x <= 180) { + containX = true; } else { - return LatLngBounds.prototype.contains.call(this, latLng); + containX = (x <= 0 && x <= west || x <= east && x>= -180); } + } else { + return LatLngBounds.prototype.contains.call(this, latLng); + } - containY = (south90 <= y90 && y90 <= north90) || //#a - (south >= 0 && north <= 0 && ((south <= y && y <= 90) || (y >= -90 && y<= north))); // #d + containY = (south90 <= y90 && y90 <= north90) || //#a + (south >= 0 && north <= 0 && ((south <= y && y <= 90) || (y >= -90 && y<= north))); // #d - return containX && containY; + return containX && containY; }; module.exports = VisibleRegion; diff --git a/www/commandQueueExecutor.js b/www/commandQueueExecutor.js index 8fc8ff256..38885d98a 100644 --- a/www/commandQueueExecutor.js +++ b/www/commandQueueExecutor.js @@ -28,28 +28,28 @@ function execCmd(success, error, pluginName, methodName, args, execOptions) { // If the overlay has been already removed from map, // do not execute any methods on it. if (overlay._isRemoved && !execOptions.remove) { - console.error("[ignore]" + pluginName + "." + methodName + ", because removed."); + console.error('[ignore]' + pluginName + '.' + methodName + ', because removed.'); return true; } // If the overlay is not ready in native side, // do not execute any methods except remove on it. // This code works for map class especially. - if (!this._isReady && methodName !== "remove") { - console.error("[ignore]" + pluginName + "." + methodName + ", because it's not ready."); + if (!this._isReady && methodName !== 'remove') { + console.error('[ignore]' + pluginName + '.' + methodName + ', because it\'s not ready.'); return true; } // Push the method into the commandQueue(FIFO) at once. commandQueue.push({ - "execOptions": execOptions, - "args": [ + 'execOptions': execOptions, + 'args': [ function() { //------------------------------- // success callback //------------------------------- - if (methodName === "resizeMap") { + if (methodName === 'resizeMap') { _isResizeMapExecuting = false; } @@ -69,7 +69,7 @@ function execCmd(success, error, pluginName, methodName, args, execOptions) { // In order to prevent this error, insert small delays. var delay = 0; if (methodName === _isWaitMethod) { - if (_isWaitMethod === "getMap" && Date.now() - _lastGetMapExecuted < 1500) { + if (_isWaitMethod === 'getMap' && Date.now() - _lastGetMapExecuted < 1500) { delay = 1500; } _lastGetMapExecuted = Date.now(); @@ -84,7 +84,7 @@ function execCmd(success, error, pluginName, methodName, args, execOptions) { //------------------------------- // error callback //------------------------------- - if (methodName === "resizeMap") { + if (methodName === 'resizeMap') { _isResizeMapExecuting = false; } if (!_stopRequested && error) { @@ -144,7 +144,7 @@ function _exec() { // If the request is `map.refreshLayout()` and another `map.refreshLayout()` is executing, // skip it. // This prevents to execute multiple `map.refreshLayout()` at the same time. - if (methodName === "resizeMap") { + if (methodName === 'resizeMap') { if (_isResizeMapExecuting) { _executingCnt--; continue; @@ -154,7 +154,7 @@ function _exec() { // If the `_stopRequested` flag is true, // do not execute any statements except `remove()` or `clear()` methods. - if (_stopRequested && (!commandParams.execOptions.remove || methodName !== "clear")) { + if (_stopRequested && (!commandParams.execOptions.remove || methodName !== 'clear')) { _executingCnt--; continue; } @@ -180,6 +180,6 @@ function stopExecution() { // Request stop all tasks. _stopRequested = true; } -window.addEventListener("unload", stopExecution); +window.addEventListener('unload', stopExecution); module.exports = execCmd; diff --git a/www/encoding.js b/www/encoding.js index 7e58e14ad..aa534761d 100644 --- a/www/encoding.js +++ b/www/encoding.js @@ -7,90 +7,90 @@ var common = require('./Common'); *****************************************************************************/ //decode function function decodePath(encoded, precision) { - precision = precision || 5; - precision = Math.pow(10, -precision); - var len = encoded.length, - index = 0, - lat = 0, - lng = 0, - array = []; - while (index < len) { - var b, shift = 0, - result = 0; - do { - b = encoded.charCodeAt(index++) - 63; - result |= (b & 0x1f) << shift; - shift += 5; - } while (b >= 0x20); - var dlat = ((result & 1) ? ~(result >> 1) : (result >> 1)); - lat += dlat; - shift = 0; - result = 0; - do { - b = encoded.charCodeAt(index++) - 63; - result |= (b & 0x1f) << shift; - shift += 5; - } while (b >= 0x20); - var dlng = ((result & 1) ? ~(result >> 1) : (result >> 1)); - lng += dlng; - array.push(new LatLng(lat * precision, lng * precision)); - } - return array; + precision = precision || 5; + precision = Math.pow(10, -precision); + var len = encoded.length, + index = 0, + lat = 0, + lng = 0, + array = []; + while (index < len) { + var b, shift = 0, + result = 0; + do { + b = encoded.charCodeAt(index++) - 63; + result |= (b & 0x1f) << shift; + shift += 5; + } while (b >= 0x20); + var dlat = ((result & 1) ? ~(result >> 1) : (result >> 1)); + lat += dlat; + shift = 0; + result = 0; + do { + b = encoded.charCodeAt(index++) - 63; + result |= (b & 0x1f) << shift; + shift += 5; + } while (b >= 0x20); + var dlng = ((result & 1) ? ~(result >> 1) : (result >> 1)); + lng += dlng; + array.push(new LatLng(lat * precision, lng * precision)); + } + return array; } //encode functions function encodePath(points) { - var plat = 0; - var plng = 0; - var encoded_points = ""; + var plat = 0; + var plng = 0; + var encoded_points = ''; - points = common.convertToPositionArray(points); + points = common.convertToPositionArray(points); - for (var i = 0; i < points.length; ++i) { - encoded_points += encodePoint(plat, plng, points[i].lat, points[i].lng); - plat = points[i].lat; - plng = points[i].lng; - } + for (var i = 0; i < points.length; ++i) { + encoded_points += encodePoint(plat, plng, points[i].lat, points[i].lng); + plat = points[i].lat; + plng = points[i].lng; + } - return encoded_points; + return encoded_points; } function encodePoint(plat, plng, lat, lng) { - var late5 = Math.round(lat * 1e5); - var plate5 = Math.round(plat * 1e5); + var late5 = Math.round(lat * 1e5); + var plate5 = Math.round(plat * 1e5); - var lnge5 = Math.round(lng * 1e5); - var plnge5 = Math.round(plng * 1e5); + var lnge5 = Math.round(lng * 1e5); + var plnge5 = Math.round(plng * 1e5); - dlng = lnge5 - plnge5; - dlat = late5 - plate5; + var dlng = lnge5 - plnge5; + var dlat = late5 - plate5; - return encodeSignedNumber(dlat) + encodeSignedNumber(dlng); + return encodeSignedNumber(dlat) + encodeSignedNumber(dlng); } function encodeSignedNumber(num) { - var sgn_num = num << 1; + var sgn_num = num << 1; - if (num < 0) { - sgn_num = ~(sgn_num); - } + if (num < 0) { + sgn_num = ~(sgn_num); + } - return (encodeNumber(sgn_num)); + return (encodeNumber(sgn_num)); } function encodeNumber(num) { - var encodeString = ""; + var encodeString = ''; - while (num >= 0x20) { - encodeString += (String.fromCharCode((0x20 | (num & 0x1f)) + 63)); - num >>= 5; - } + while (num >= 0x20) { + encodeString += (String.fromCharCode((0x20 | (num & 0x1f)) + 63)); + num >>= 5; + } - encodeString += (String.fromCharCode(num + 63)); - return encodeString; + encodeString += (String.fromCharCode(num + 63)); + return encodeString; } module.exports = { - decodePath: decodePath, - encodePath: encodePath + decodePath: decodePath, + encodePath: encodePath }; diff --git a/www/event.js b/www/event.js index 3c0799bed..76f9dcb3a 100644 --- a/www/event.js +++ b/www/event.js @@ -1,34 +1,34 @@ module.exports = { - MAP_READY: 'map_ready', - MAP_CLICK: 'map_click', - MAP_LONG_CLICK: 'map_long_click', - POI_CLICK: 'poi_click', - MY_LOCATION_CLICK: 'my_location_click', - MY_LOCATION_BUTTON_CLICK: 'my_location_button_click', - INDOOR_BUILDING_FOCUSED: 'indoor_building_focused', - INDOOR_LEVEL_ACTIVATED: 'indoor_level_activated', - CAMERA_MOVE_START: 'camera_move_start', - CAMERA_MOVE: 'camera_move', - CAMERA_MOVE_END: 'camera_move_end', - OVERLAY_CLICK: 'overlay_click', - POLYGON_CLICK: 'polygon_click', - POLYLINE_CLICK: 'polyline_click', - CIRCLE_CLICK: 'circle_click', - GROUND_OVERLAY_CLICK: 'groundoverlay_click', - INFO_CLICK: 'info_click', - INFO_LONG_CLICK: 'info_long_click', - INFO_CLOSE: 'info_close', - INFO_OPEN: 'info_open', - MARKER_CLICK: 'marker_click', - MARKER_DRAG: 'marker_drag', - MARKER_DRAG_START: 'marker_drag_start', - MARKER_DRAG_END: 'marker_drag_end', - MAP_DRAG: 'map_drag', - MAP_DRAG_START: 'map_drag_start', - MAP_DRAG_END: 'map_drag_end', - KML_CLICK: 'kml_click', - PANORAMA_READY: 'panorama_ready', - PANORAMA_CAMERA_CHANGE: 'panorama_camera_change', - PANORAMA_LOCATION_CHANGE: 'panorama_location_change', - PANORAMA_CLICK: 'panorama_click' + MAP_READY: 'map_ready', + MAP_CLICK: 'map_click', + MAP_LONG_CLICK: 'map_long_click', + POI_CLICK: 'poi_click', + MY_LOCATION_CLICK: 'my_location_click', + MY_LOCATION_BUTTON_CLICK: 'my_location_button_click', + INDOOR_BUILDING_FOCUSED: 'indoor_building_focused', + INDOOR_LEVEL_ACTIVATED: 'indoor_level_activated', + CAMERA_MOVE_START: 'camera_move_start', + CAMERA_MOVE: 'camera_move', + CAMERA_MOVE_END: 'camera_move_end', + OVERLAY_CLICK: 'overlay_click', + POLYGON_CLICK: 'polygon_click', + POLYLINE_CLICK: 'polyline_click', + CIRCLE_CLICK: 'circle_click', + GROUND_OVERLAY_CLICK: 'groundoverlay_click', + INFO_CLICK: 'info_click', + INFO_LONG_CLICK: 'info_long_click', + INFO_CLOSE: 'info_close', + INFO_OPEN: 'info_open', + MARKER_CLICK: 'marker_click', + MARKER_DRAG: 'marker_drag', + MARKER_DRAG_START: 'marker_drag_start', + MARKER_DRAG_END: 'marker_drag_end', + MAP_DRAG: 'map_drag', + MAP_DRAG_START: 'map_drag_start', + MAP_DRAG_END: 'map_drag_end', + KML_CLICK: 'kml_click', + PANORAMA_READY: 'panorama_ready', + PANORAMA_CAMERA_CHANGE: 'panorama_camera_change', + PANORAMA_LOCATION_CHANGE: 'panorama_location_change', + PANORAMA_CLICK: 'panorama_click' }; diff --git a/www/geomodel.js b/www/geomodel.js index f956b486f..5a285886d 100644 --- a/www/geomodel.js +++ b/www/geomodel.js @@ -13,18 +13,16 @@ # 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 LatLng = require('./LatLng'); -var LatLngBounds = require('./LatLngBounds'); -var common = require('./Common'); +*/ -var GEOCELL_GRID_SIZE = 4; -var GEOCELL_ALPHABET = "0123456789abcdef"; +var LatLng = require('./LatLng'), + LatLngBounds = require('./LatLngBounds'), + GEOCELL_GRID_SIZE = 4, + GEOCELL_ALPHABET = '0123456789abcdef'; function computeBox(geocell) { var subcell_lng_span, subcell_lat_span; - var xy, x, y, i; + var xy, x, y; var bbox = _createBoundingBox(90.0, 180.0, -90.0, -180.0); while(geocell.length > 0) { //geoChar = geocell.charAt(i); @@ -38,9 +36,9 @@ function computeBox(geocell) { y = xy[1]; bbox = _createBoundingBox(bbox.getSouth() + subcell_lat_span * (y + 1), - bbox.getWest() + subcell_lng_span * (x + 1), - bbox.getSouth() + subcell_lat_span * y, - bbox.getWest() + subcell_lng_span * x); + bbox.getWest() + subcell_lng_span * (x + 1), + bbox.getSouth() + subcell_lat_span * y, + bbox.getWest() + subcell_lng_span * x); geocell = geocell.substring(1); } @@ -86,7 +84,7 @@ function _createBoundingBox(north, east, south, west) { * @return */ function getGeocell(lat, lng, resolution) { - var cell = ""; + var cell = ''; var north = 90.0; var south = -90.0; var east = 180.0; @@ -102,7 +100,6 @@ function getGeocell(lat, lng, resolution) { y = Math.min(Math.floor(GEOCELL_GRID_SIZE * (lat - south) / (north - south)),GEOCELL_GRID_SIZE - 1); cell += _subdiv_char(x, y); - south += subcell_lat_span * y; north = south + subcell_lat_span; @@ -120,7 +117,7 @@ function _subdiv_xy(char) { // NOTE: This only works for grid size 4. var charI = GEOCELL_ALPHABET.indexOf(char); return [(charI & 4) >> 1 | (charI & 1) >> 0, - (charI & 8) >> 2 | (charI & 2) >> 1]; + (charI & 8) >> 2 | (charI & 2) >> 1]; } /** @@ -130,13 +127,13 @@ function _subdiv_xy(char) { function _subdiv_char(posX, posY) { // NOTE: This only works for grid size 4. return GEOCELL_ALPHABET.charAt( - (posY & 2) << 2 | - (posX & 2) << 1 | - (posY & 1) << 1 | - (posX & 1) << 0); + (posY & 2) << 2 | + (posX & 2) << 1 | + (posY & 1) << 1 | + (posX & 1) << 0); } module.exports = { - computeBox: computeBox, - getGeocell: getGeocell + computeBox: computeBox, + getGeocell: getGeocell }; diff --git a/www/js_CordovaGoogleMaps-for-android_ios.js b/www/js_CordovaGoogleMaps-for-android_ios.js index 9ef1712e0..64ef11734 100644 --- a/www/js_CordovaGoogleMaps-for-android_ios.js +++ b/www/js_CordovaGoogleMaps-for-android_ios.js @@ -15,7 +15,7 @@ function CordovaGoogleMaps(execCmd) { // Ignore checking for thse tags. self.doNotTraceTags = [ - "svg", "p", "pre", "script", "style" + 'svg', 'p', 'pre', 'script', 'style' ]; self.execCmd = execCmd; @@ -41,7 +41,7 @@ function CordovaGoogleMaps(execCmd) { self.isThereAnyChange = false; // Indicate the native timer is stopped or not. - self.set("isSuspended", false); + self.set('isSuspended', false); // Cache for updateMapPositionOnly self.prevMapRects = {}; @@ -57,14 +57,13 @@ function CordovaGoogleMaps(execCmd) { //------------------------------------------------------------------------------ var observer = new MutationObserver(function(mutations) { common.nextTick(function() { - // Since Android 4.4 passes mutations as "Object", not "Array", - // use "for" statement instead of "forEach" method. + // Since Android 4.4 passes mutations as 'Object', not 'Array', + // use 'for' statement instead of 'forEach' method. - var i, mutation, node, j, elemId, doTraceTree = true; + var i, mutation, node, j, doTraceTree = true; for (j = 0; j < mutations.length; j++) { mutation = mutations[j]; - targetCnt = 0; - if (mutation.type === "childList") { + if (mutation.type === 'childList') { // If some elements are added, check them. if (mutation.addedNodes) { for (i = 0; i < mutation.addedNodes.length; i++) { @@ -80,7 +79,7 @@ function CordovaGoogleMaps(execCmd) { if (mutation.removedNodes) { for (i = 0; i < mutation.removedNodes.length; i++) { node = mutation.removedNodes[i]; - if (node.nodeType !== Node.ELEMENT_NODE || !node.hasAttribute("__pluginDomId")) { + if (node.nodeType !== Node.ELEMENT_NODE || !node.hasAttribute('__pluginDomId')) { continue; } node._isRemoved = true; @@ -93,14 +92,14 @@ function CordovaGoogleMaps(execCmd) { if (mutation.target.nodeType !== Node.ELEMENT_NODE) { continue; } - if (mutation.target.hasAttribute("__pluginDomId")) { - elemId = mutation.target.getAttribute("__pluginDomId"); - var transformCSS = common.getStyle(mutation.target, "transform") || - common.getStyle(mutation.target, "-webkit-transform") || - common.getStyle(mutation.target, "transition") || - common.getStyle(mutation.target, "-webkit-transition"); - if (transformCSS !== "none") { - mutation.target.dispatchEvent(common.createEvent("transitionstart")); + if (mutation.target.hasAttribute('__pluginDomId')) { + // elemId = mutation.target.getAttribute('__pluginDomId'); + var transformCSS = common.getStyle(mutation.target, 'transform') || + common.getStyle(mutation.target, '-webkit-transform') || + common.getStyle(mutation.target, 'transition') || + common.getStyle(mutation.target, '-webkit-transition'); + if (transformCSS !== 'none') { + mutation.target.dispatchEvent(common.createEvent('transitionstart')); // Omit executing the putHtmlElements() at this time, // because it is executed at `transitionend`. @@ -124,9 +123,9 @@ function CordovaGoogleMaps(execCmd) { attributeFilter: ['style', 'class'] }); }; - self.one("start", attachObserver); + self.one('start', attachObserver); - self.on("isSuspended_changed", function(oldValue, newValue) { + self.on('isSuspended_changed', function(oldValue, newValue) { if (newValue) { cordova_exec(null, null, 'CordovaGoogleMaps', 'pause', []); } else { @@ -162,7 +161,7 @@ CordovaGoogleMaps.prototype.traceDomTree = function(element, elemId, isMapChild) pointerEvents: common.getStyle(element, 'pointer-events'), // Only true if element is mapDiv - isMap: element.hasAttribute("__pluginMapId"), + isMap: element.hasAttribute('__pluginMapId'), // Calculate dom clickable region size: common.getDivRect(element), @@ -171,8 +170,8 @@ CordovaGoogleMaps.prototype.traceDomTree = function(element, elemId, isMapChild) zIndex: zIndexProp, // If `overflow: hidden or scroll`, the native side needs to recalculate actual size - overflowX: common.getStyle(element, "overflow-x"), - overflowY: common.getStyle(element, "overflow-y"), + overflowX: common.getStyle(element, 'overflow-x'), + overflowY: common.getStyle(element, 'overflow-y'), // Hold the elementId of child elements children: [], @@ -190,14 +189,14 @@ CordovaGoogleMaps.prototype.traceDomTree = function(element, elemId, isMapChild) // check all elements, especially for HtmlInfoWindow. // // - condition 3: - // If the pointer-css is "none", continue the proces, + // If the pointer-css is 'none', continue the proces, // because the element might be a container of the map. // // - condition 4: - // If the z-index is "inherit", there might be some elements. + // If the z-index is 'inherit', there might be some elements. var containMapCnt = (Object.keys(self.domPositions[elemId].containMapIDs)).length; isMapChild = isMapChild || self.domPositions[elemId].isMap; - if ((containMapCnt > 0 || isMapChild || self.domPositions[elemId].pointerEvents === "none" || zIndexProp.isInherit) && element.children.length > 0) { + if ((containMapCnt > 0 || isMapChild || self.domPositions[elemId].pointerEvents === 'none' || zIndexProp.isInherit) && element.children.length > 0) { var child; for (var i = 0; i < element.children.length; i++) { child = element.children[i]; @@ -274,7 +273,7 @@ CordovaGoogleMaps.prototype.putHtmlElements = function() { isTouchable = false; } } - map.set("__isAttached", isTouchable); + map.set('__isAttached', isTouchable); } return isTouchable; }); @@ -294,25 +293,25 @@ CordovaGoogleMaps.prototype.putHtmlElements = function() { return; } - // Since the native side needs to know the "latest" DOM information, + // Since the native side needs to know the 'latest' DOM information, // clear the DOM cache. common._clearInternalCache(); // Generate the DOM hierarchy tree from tag. common.getPluginDomId(document.body); - self.traceDomTree.call(self, document.body, "root", false); + self.traceDomTree.call(self, document.body, 'root', false); // If the map div is not displayed (such as display='none'), // ignore the map temporally. var stopFlag = false; - var mapElemIDs = mapIDs.map(function(mapId) { + mapIDs.forEach(function(mapId) { var div = self.MAPS[mapId].getDiv(); if (!div || stopFlag) { return; } // Does this dom is really existed? - var elemId = div.getAttribute("__pluginDomId"); + var elemId = div.getAttribute('__pluginDomId'); if (!elemId) { // The map div is removed if (mapId in self.MAPS) { @@ -324,7 +323,7 @@ CordovaGoogleMaps.prototype.putHtmlElements = function() { if (!(elemId in self.domPositions)) { // Is the map div removed? - var ele = document.querySelector("[__pluginMapId='" + mapId + "']"); + var ele = document.querySelector('[__pluginMapId="' + mapId + '"]'); if (!ele) { // If no div element, remove the map. if (mapId in self.MAPS) { @@ -333,8 +332,6 @@ CordovaGoogleMaps.prototype.putHtmlElements = function() { stopFlag = true; } return; - } else { - return elemId; } }); @@ -356,9 +353,9 @@ CordovaGoogleMaps.prototype.putHtmlElements = function() { //----------------------------------------------------------------- self.resume(); - //console.log("--->putHtmlElements to native (start)", JSON.parse(JSON.stringify(self.domPositions))); + //console.log('--->putHtmlElements to native (start)', JSON.parse(JSON.stringify(self.domPositions))); cordova_exec(function() { - //console.log("--->putHtmlElements to native (done)"); + //console.log('--->putHtmlElements to native (done)'); // If there is another checking request, try again. if (self.checkRequested) { @@ -382,14 +379,14 @@ CordovaGoogleMaps.prototype.putHtmlElements = function() { CordovaGoogleMaps.prototype.pause = function() { var self = this; - self.set("isSuspended", true); + self.set('isSuspended', true); self.isThereAnyChange = false; self.isChecking = false; }; CordovaGoogleMaps.prototype.resume = function() { var self = this; - self.set("isSuspended", false); + self.set('isSuspended', false); }; @@ -416,7 +413,7 @@ CordovaGoogleMaps.prototype.followMaps = function(evt) { }; // CSS event `transitionend` is fired even the target dom element is still moving. -// In order to detect "correct demention after the transform", wait until stable. +// In order to detect 'correct demention after the transform', wait until stable. CordovaGoogleMaps.prototype.onTransitionEnd = function(evt) { var self = this; if (self.MAP_CNT === 0 || !evt) { @@ -426,8 +423,8 @@ CordovaGoogleMaps.prototype.onTransitionEnd = function(evt) { if (!target) { target = document.body; } - target = target.getAttribute === "function" ? target : document.body; - var elemId = target.getAttribute("__pluginDomId"); + target = target.getAttribute === 'function' ? target : document.body; + var elemId = target.getAttribute('__pluginDomId'); self.transformTargets[elemId] = {left: -1, top: -1, right: -1, bottom: -1, finish: false, target: target}; if (!self.transitionEndTimer) { self.transitionEndTimer = setTimeout(self.detectTransitionFinish.bind(self), 100); @@ -531,7 +528,7 @@ CordovaGoogleMaps.prototype.removeDomTree = function(node) { // If map div, remove the map also. if (child.hasAttribute('__pluginMapId')) { - mapId = child.getAttribute('__pluginMapId'); + var mapId = child.getAttribute('__pluginMapId'); if (mapId in self.MAPS) { self.MAPS[mapId].remove(); } @@ -582,7 +579,7 @@ CordovaGoogleMaps.prototype.followMapDivPositionOnly = function(opts) { // Obtain only minimum information var mapDiv = map.getDiv(); - var divId = mapDiv.getAttribute("__pluginDomId"); + var divId = mapDiv.getAttribute('__pluginDomId'); mapRects[divId] = { size: common.getDivRect(mapDiv), zIndex: common.getZIndex(mapDiv) @@ -591,23 +588,23 @@ CordovaGoogleMaps.prototype.followMapDivPositionOnly = function(opts) { // Is the map moved? if (!changed && self.prevMapRects && divId in self.prevMapRects) { if (self.prevMapRects[divId].size.left !== mapRects[divId].size.left) { - //console.log("changed(left)", divId, self.prevMapRects[divId].size.left, mapRects[divId].size.left); + //console.log('changed(left)', divId, self.prevMapRects[divId].size.left, mapRects[divId].size.left); changed = true; } if (!changed && self.prevMapRects[divId].size.top !== mapRects[divId].size.top) { - //console.log("changed(top)", divId, self.prevMapRects[divId].size.top, mapRects[divId].size.top); + //console.log('changed(top)', divId, self.prevMapRects[divId].size.top, mapRects[divId].size.top); changed = true; } if (!changed && self.prevMapRects[divId].size.width !== mapRects[divId].size.width) { - //console.log("changed(width)", divId, self.prevMapRects[divId].size.width, mapRects[divId].size.width); + //console.log('changed(width)', divId, self.prevMapRects[divId].size.width, mapRects[divId].size.width); changed = true; } if (!changed && self.prevMapRects[divId].size.height !== mapRects[divId].size.height) { - //console.log("changed(height)", divId, self.prevMapRects[divId].size.height, mapRects[divId].size.height); + //console.log('changed(height)', divId, self.prevMapRects[divId].size.height, mapRects[divId].size.height); changed = true; } if (!changed && self.prevMapRects[divId].zIndex.z !== mapRects[divId].zIndex.z) { - //console.log("changed(zIndex.z)", divId, self.prevMapRects[divId].zIndex.z, mapRects[divId].zIndex.z); + //console.log('changed(zIndex.z)', divId, self.prevMapRects[divId].zIndex.z, mapRects[divId].zIndex.z); changed = true; } } @@ -644,8 +641,6 @@ CordovaGoogleMaps.prototype.invalidateN = function(cnt) { CordovaGoogleMaps.prototype.getMap = function(div, mapOptions) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); //---------------------------------------------------------------------------- // This procedure return a map instance. @@ -660,10 +655,11 @@ CordovaGoogleMaps.prototype.getMap = function(div, mapOptions) { // In order to keep the backward compatibility for v1, // if the mapDiv has already a map, returns the map instance for the map div. //---------------------------------------------------------------------------- - var mapId, elem, elemId; + var self = this, + mapId, elem, elemId; if (common.isDom(div)) { - mapId = div.getAttribute("__pluginMapId"); + mapId = div.getAttribute('__pluginMapId'); // Wow, the app specifies the map div that has already another map, // but the app try to create new map. @@ -671,7 +667,7 @@ CordovaGoogleMaps.prototype.getMap = function(div, mapOptions) { if (mapId && self.MAPS[mapId].getDiv() !== div) { elem = self.MAPS[mapId].getDiv(); while(elem && elem.nodeType === Node.ELEMENT_NODE) { - elemId = elem.getAttribute("__pluginDomId"); + elemId = elem.getAttribute('__pluginDomId'); if (elemId && elemId in self.domPositions) { self.domPositions[elemId].containMapIDs = self.domPositions[elemId].containMapIDs || {}; delete self.domPositions[elemId].containMapIDs[mapId]; @@ -694,7 +690,7 @@ CordovaGoogleMaps.prototype.getMap = function(div, mapOptions) { } if (!mapId) { - mapId = "map_" + self.MAP_CNT + "_" + self.saltHash; + mapId = 'map_' + self.MAP_CNT + '_' + self.saltHash; } // Create a map instance. var map = new Map(mapId, self.execCmd); @@ -702,7 +698,7 @@ CordovaGoogleMaps.prototype.getMap = function(div, mapOptions) { // Catch all events for this map instance, then pass to the instance. // (Don't execute this native callback from your code) - plugin.google.maps[mapId] = nativeCallback.bind(map); + window.plugin.google.maps[mapId] = nativeCallback.bind(map); map.on('__isAttached_changed', function(oldValue, newValue) { if (newValue) { @@ -733,8 +729,8 @@ CordovaGoogleMaps.prototype.getMap = function(div, mapOptions) { if (ele.classList) { ele.classList.remove('_gmaps_cdv_'); } else if (ele.className) { - ele.className = ele.className.replace(/_gmaps_cdv_/g, ""); - ele.className = ele.className.replace(/\s+/g, " "); + ele.className = ele.className.replace(/_gmaps_cdv_/g, ''); + ele.className = ele.className.replace(/\s+/g, ' '); } ele = ele.parentNode; } @@ -750,8 +746,8 @@ CordovaGoogleMaps.prototype.getMap = function(div, mapOptions) { elemId = common.getPluginDomId(elem); if (common.shouldWatchByNative(elem)) { if (elem.shadowRoot) { - elem.shadowRoot.addEventListener("transitionend", self.onTransitionEnd.bind(self), {capture: true}); - elem.shadowRoot.addEventListener("scroll", self.followMaps.bind(self), {capture: true}); + elem.shadowRoot.addEventListener('transitionend', self.onTransitionEnd.bind(self), {capture: true}); + elem.shadowRoot.addEventListener('scroll', self.followMaps.bind(self), {capture: true}); } isCached = elemId in self.domPositions; self.domPositions[elemId] = { @@ -760,8 +756,8 @@ CordovaGoogleMaps.prototype.getMap = function(div, mapOptions) { size: common.getDivRect(elem), zIndex: common.getZIndex(elem), children: (elemId in self.domPositions ? self.domPositions[elemId].children : []), - overflowX: common.getStyle(elem, "overflow-x"), - overflowY: common.getStyle(elem, "overflow-y"), + overflowX: common.getStyle(elem, 'overflow-x'), + overflowY: common.getStyle(elem, 'overflow-y'), containMapIDs: (isCached ? self.domPositions[elemId].containMapIDs : {}) }; self.domPositions[elemId].containMapIDs[mapId] = 1; @@ -800,14 +796,14 @@ CordovaGoogleMaps.prototype.getMap = function(div, mapOptions) { CordovaGoogleMaps.prototype.getPanorama = function(div, streetViewOptions) { var self = this; - var mapId = "streetview_" + self.MAP_CNT + "_" + self.saltHash; + var mapId = 'streetview_' + self.MAP_CNT + '_' + self.saltHash; // Create a panorama instance. var panorama = new StreetViewPanorama(mapId, self.execCmd); // Catch all events for this map instance, then pass to the instance. // (Don't execute this native callback from your code) - plugin.google.maps[mapId] = nativeCallback.bind(panorama); + window.plugin.google.maps[mapId] = nativeCallback.bind(panorama); self.MAP_CNT++; @@ -832,12 +828,12 @@ CordovaGoogleMaps.prototype.getPanorama = function(div, streetViewOptions) { CordovaGoogleMaps.prototype._remove = function(mapId) { var self = this; - delete plugin.google.maps[mapId]; + delete window.plugin.google.maps[mapId]; var map = self.MAPS[mapId]; var div = map.getDiv(); if (!div) { - div = document.querySelector("[__pluginMapId='" + mapId + "']"); + div = document.querySelector('[__pluginMapId="' + mapId + '"]'); } if (div) { div.removeAttribute('__pluginMapId'); @@ -881,7 +877,7 @@ function postPanoramaInit(panorama, div, options) { // If the given div is not fully ready, wait a little if (!common.shouldWatchByNative(div)) { setTimeout(function() { - common.nextTick(postPanoramaInit.bind(self, map, div, options)); + common.nextTick(postPanoramaInit.bind(self, panorama, div, options)); }, 50); return; } @@ -893,10 +889,10 @@ function postPanoramaInit(panorama, div, options) { // If the mapDiv is specified, // the native side needs to know the map div position // before creating the map view. - div.setAttribute("__pluginMapId", mapId); - elemId = common.getPluginDomId(div); + div.setAttribute('__pluginMapId', mapId); + var elemId = common.getPluginDomId(div); - elem = div; + var elem = div; var isCached, zIndexList = []; while(elem && elem.nodeType === Node.ELEMENT_NODE) { elemId = common.getPluginDomId(elem); @@ -908,8 +904,8 @@ function postPanoramaInit(panorama, div, options) { size: common.getDivRect(elem), zIndex: common.getZIndex(elem), children: [], - overflowX: common.getStyle(elem, "overflow-x"), - overflowY: common.getStyle(elem, "overflow-y"), + overflowX: common.getStyle(elem, 'overflow-x'), + overflowY: common.getStyle(elem, 'overflow-y'), containMapIDs: (isCached ? self.domPositions[elemId].containMapIDs : {}) }; zIndexList.unshift(self.domPositions[elemId].zIndex); @@ -966,7 +962,7 @@ function postMapInit(map, div, options) { // If the mapDiv is specified, // the native side needs to know the map div position // before creating the map view. - div.setAttribute("__pluginMapId", mapId); + div.setAttribute('__pluginMapId', mapId); var elemId = common.getPluginDomId(div); var elem = div; @@ -982,8 +978,8 @@ function postMapInit(map, div, options) { size: common.getDivRect(elem), zIndex: common.getZIndex(elem), children: [], - overflowX: common.getStyle(elem, "overflow-x"), - overflowY: common.getStyle(elem, "overflow-y"), + overflowX: common.getStyle(elem, 'overflow-x'), + overflowY: common.getStyle(elem, 'overflow-y'), containMapIDs: (isCached ? self.domPositions[elemId].containMapIDs : {}) }; zIndexList.unshift(self.domPositions[elemId].zIndex); diff --git a/www/js_CordovaGoogleMaps-for-browser.js b/www/js_CordovaGoogleMaps-for-browser.js index 659f5c552..4dbe3bc51 100644 --- a/www/js_CordovaGoogleMaps-for-browser.js +++ b/www/js_CordovaGoogleMaps-for-browser.js @@ -69,8 +69,6 @@ function CordovaGoogleMaps(execCmd) { } CordovaGoogleMaps.prototype.getMap = function(div, mapOptions) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); //---------------------------------------------------------------------------- // This procedure return a map instance. @@ -85,10 +83,11 @@ CordovaGoogleMaps.prototype.getMap = function(div, mapOptions) { // In order to keep the backward compatibility for v1, // if the mapDiv has already a map, returns the map instance for the map div. //---------------------------------------------------------------------------- - var mapId, elem, elemId; + var self = this, + mapId; if (common.isDom(div)) { - mapId = div.getAttribute("__pluginMapId"); + mapId = div.getAttribute('__pluginMapId'); // Wow, the app specifies the map div that has already another map, // but the app try to create new map. @@ -113,11 +112,11 @@ CordovaGoogleMaps.prototype.getMap = function(div, mapOptions) { } if (!mapId) { - mapId = "map_" + self.MAP_CNT + "_" + self.saltHash; + mapId = 'map_' + self.MAP_CNT + '_' + self.saltHash; } // Create a map instance. var map = new Map(mapId, self.execCmd); - plugin.google.maps[mapId] = nativeCallback.bind(map); + window.plugin.google.maps[mapId] = nativeCallback.bind(map); // If the map is removed, clean up the information. map.one('remove', self._remove.bind(self, mapId)); @@ -143,14 +142,14 @@ CordovaGoogleMaps.prototype.getMap = function(div, mapOptions) { CordovaGoogleMaps.prototype.getPanorama = function(div, streetViewOptions) { var self = this; - var mapId = "streetview_" + self.MAP_CNT + "_" + self.saltHash; + var mapId = 'streetview_' + self.MAP_CNT + '_' + self.saltHash; // Create a panorama instance. var panorama = new StreetViewPanorama(mapId, self.execCmd); // Catch all events for this map instance, then pass to the instance. // (Don't execute this native callback from your code) - plugin.google.maps[mapId] = nativeCallback.bind(panorama); + window.plugin.google.maps[mapId] = nativeCallback.bind(panorama); self.MAP_CNT++; panorama.one('remove', self._remove.bind(self, mapId)); @@ -177,7 +176,7 @@ CordovaGoogleMaps.prototype._remove = function(mapId) { var div = map.getDiv(); if (!div) { - div = document.querySelector("[__pluginMapId='" + mapId + "']"); + div = document.querySelector('[__pluginMapId="' + mapId + '"]'); } if (div) { div.removeAttribute('__pluginMapId'); @@ -200,7 +199,7 @@ function postPanoramaInit(panorama, div, options) { // If the given div is not fully ready, wait a little if (!common.shouldWatchByNative(div)) { setTimeout(function() { - common.nextTick(postPanoramaInit.bind(self, map, div, options)); + common.nextTick(postPanoramaInit.bind(self, panorama, div, options)); }, 50); return; } @@ -212,7 +211,7 @@ function postPanoramaInit(panorama, div, options) { // If the mapDiv is specified, // the native side needs to know the map div position // before creating the map view. - div.setAttribute("__pluginMapId", mapId); + div.setAttribute('__pluginMapId', mapId); if (div.offsetWidth < 100 || div.offsetHeight < 100) { console.error('[GoogleMaps] Minimum container dimention is 100x100 in pixels.', div); @@ -226,7 +225,7 @@ function postPanoramaInit(panorama, div, options) { // If the mapDiv is specified, // the native side needs to know the map div position // before creating the map view. - div.setAttribute("__pluginMapId", mapId); + div.setAttribute('__pluginMapId', mapId); panorama.getPanorama.apply(panorama, args); } @@ -251,7 +250,7 @@ function postMapInit(map, div, options) { // If the mapDiv is specified, // the native side needs to know the map div position // before creating the map view. - div.setAttribute("__pluginMapId", mapId); + div.setAttribute('__pluginMapId', mapId); args.push({ id: mapId, diff --git a/www/plugin-loader-for-android_ios.js b/www/plugin-loader-for-android_ios.js index 2bdd584a5..2fc724667 100644 --- a/www/plugin-loader-for-android_ios.js +++ b/www/plugin-loader-for-android_ios.js @@ -1,7 +1,5 @@ - -/* global cordova, plugin, CSSPrimitiveValue */ if (!cordova) { - document.addEventListener("deviceready", function() { + document.addEventListener('deviceready', function () { require('cordova/exec')(null, null, 'CordovaGoogleMaps', 'pause', []); }, { once: true @@ -9,36 +7,44 @@ if (!cordova) { } else { var common = require('./Common'); // The pluginInit.js must execute before loading HTML is completed. - require("./pluginInit")(); + require('./pluginInit')(); - cordova.addConstructor(function() { + cordova.addConstructor(function () { if (!window.Cordova) { - window.Cordova = cordova; + window.Cordova = cordova; } window.plugin = window.plugin || {}; window.plugin.google = window.plugin.google || {}; window.plugin.google.maps = window.plugin.google.maps || module.exports; - - document.addEventListener("deviceready", function() { + document.addEventListener('deviceready', function () { // workaround for issue on android-19: Cannot read property 'maps' of undefined - if (!window.plugin) { console.warn('re-init window.plugin'); window.plugin = window.plugin || {}; } - if (!window.plugin.google) { console.warn('re-init window.plugin.google'); window.plugin.google = window.plugin.google || {}; } - if (!window.plugin.google.maps) { console.warn('re-init window.plugin.google.maps'); window.plugin.google.maps = window.plugin.google.maps || module.exports; } + if (!window.plugin) { + console.warn('re-init window.plugin'); + window.plugin = window.plugin || {}; + } + if (!window.plugin.google) { + console.warn('re-init window.plugin.google'); + window.plugin.google = window.plugin.google || {}; + } + if (!window.plugin.google.maps) { + console.warn('re-init window.plugin.google.maps'); + window.plugin.google.maps = window.plugin.google.maps || module.exports; + } - cordova.exec(null, function(message) { - alert(message); + cordova.exec(null, function (message) { + alert(message); }, 'PluginEnvironment', 'isAvailable', ['']); }, { once: true }); }); - var execCmd = require("./commandQueueExecutor"); - var cordovaGoogleMaps = new (require('./js_CordovaGoogleMaps'))(execCmd); + var execCmd = require('./commandQueueExecutor'); + var cordovaGoogleMaps = new(require('./js_CordovaGoogleMaps'))(execCmd); - (new Promise(function(resolve) { - var wait = function() { + (new Promise(function (resolve) { + var wait = function () { if (document.body) { wait = undefined; cordovaGoogleMaps.trigger('start'); @@ -49,14 +55,14 @@ if (!cordova) { }; wait(); - })).then(function() { - common.nextTick(function() { + })).then(function () { + common.nextTick(function () { // If the developer needs to recalculate the DOM tree graph, // use `cordova.fireDocumentEvent('plugin_touch')` - document.addEventListener("plugin_touch", cordovaGoogleMaps.invalidate.bind(cordovaGoogleMaps)); + document.addEventListener('plugin_touch', cordovaGoogleMaps.invalidate.bind(cordovaGoogleMaps)); // Repositioning 30 times when the device orientaion is changed. - window.addEventListener("orientationchange", cordovaGoogleMaps.followMaps.bind(cordovaGoogleMaps, { + window.addEventListener('orientationchange', cordovaGoogleMaps.followMaps.bind(cordovaGoogleMaps, { target: document.body })); @@ -66,11 +72,14 @@ if (!cordova) { // return; // } - - document.addEventListener("transitionstart", cordovaGoogleMaps.followMaps.bind(cordovaGoogleMaps), {capture: true}); - document.body.parentNode.addEventListener("transitionend", cordovaGoogleMaps.onTransitionEnd.bind(cordovaGoogleMaps), {capture: true}); - // document.body.addEventListener("transitionend", function(e) { - // if (!e.target.hasAttribute("__pluginDomId")) { + document.addEventListener('transitionstart', cordovaGoogleMaps.followMaps.bind(cordovaGoogleMaps), { + capture: true + }); + document.body.parentNode.addEventListener('transitionend', cordovaGoogleMaps.onTransitionEnd.bind(cordovaGoogleMaps), { + capture: true + }); + // document.body.addEventListener('transitionend', function(e) { + // if (!e.target.hasAttribute('__pluginDomId')) { // return; // } // cordovaGoogleMaps.invalidateN(5); @@ -78,8 +87,8 @@ if (!cordova) { // If the `scroll` event is ocurred on the observed element, // adjust the position and size of the map view - document.body.parentNode.addEventListener("scroll", cordovaGoogleMaps.followMaps.bind(cordovaGoogleMaps), true); - window.addEventListener("resize", function() { + document.body.parentNode.addEventListener('scroll', cordovaGoogleMaps.followMaps.bind(cordovaGoogleMaps), true); + window.addEventListener('resize', function () { cordovaGoogleMaps.transforming = true; cordovaGoogleMaps.onTransitionFinish.call(cordovaGoogleMaps); }, true); @@ -94,8 +103,8 @@ if (!cordova) { module.exports = { event: require('./event'), Animation: { - BOUNCE: 'BOUNCE', - DROP: 'DROP' + BOUNCE: 'BOUNCE', + DROP: 'DROP' }, BaseClass: require('./BaseClass'), @@ -118,9 +127,9 @@ if (!cordova) { Geocoder: require('./Geocoder')(execCmd), LocationService: require('./LocationService')(execCmd), geometry: { - encoding: require('./encoding'), - spherical: require('./spherical'), - poly: require('./poly') + encoding: require('./encoding'), + spherical: require('./spherical'), + poly: require('./poly') } }; } diff --git a/www/plugin-loader-for-browser.js b/www/plugin-loader-for-browser.js index f0f953304..87d636a1f 100644 --- a/www/plugin-loader-for-browser.js +++ b/www/plugin-loader-for-browser.js @@ -1,20 +1,14 @@ - -var event = require('cordova-plugin-googlemaps.event'); - -var Map = require('cordova-plugin-googlemaps.Map'), +var event = require('cordova-plugin-googlemaps.event'), BaseClass = require('cordova-plugin-googlemaps.BaseClass'), - BaseArrayClass = require('cordova-plugin-googlemaps.BaseArrayClass'); - -var cordova_exec = require('cordova/exec'); - -var execCmd = require("cordova-plugin-googlemaps.commandQueueExecutor"); -var cordovaGoogleMaps = new (require('cordova-plugin-googlemaps.js_CordovaGoogleMaps'))(execCmd); + BaseArrayClass = require('cordova-plugin-googlemaps.BaseArrayClass'), + execCmd = require('cordova-plugin-googlemaps.commandQueueExecutor'), + cordovaGoogleMaps = new(require('cordova-plugin-googlemaps.js_CordovaGoogleMaps'))(execCmd); module.exports = { event: event, Animation: { - BOUNCE: 'BOUNCE', - DROP: 'DROP' + BOUNCE: 'BOUNCE', + DROP: 'DROP' }, BaseClass: BaseClass, BaseArrayClass: BaseArrayClass, @@ -36,16 +30,15 @@ module.exports = { Geocoder: require('cordova-plugin-googlemaps.Geocoder')(execCmd), LocationService: require('cordova-plugin-googlemaps.LocationService')(execCmd), geometry: { - encoding: require('cordova-plugin-googlemaps.encoding'), - spherical: require('cordova-plugin-googlemaps.spherical'), - poly: require('cordova-plugin-googlemaps.poly') + encoding: require('cordova-plugin-googlemaps.encoding'), + spherical: require('cordova-plugin-googlemaps.spherical'), + poly: require('cordova-plugin-googlemaps.poly') } }; - -cordova.addConstructor(function() { +cordova.addConstructor(function () { if (!window.Cordova) { - window.Cordova = cordova; + window.Cordova = cordova; } window.plugin = window.plugin || {}; window.plugin.google = window.plugin.google || {}; diff --git a/www/pluginInit.js b/www/pluginInit.js index ccbef139c..10fe61212 100644 --- a/www/pluginInit.js +++ b/www/pluginInit.js @@ -1,4 +1,5 @@ var cordova_exec = require('cordova/exec'); + function pluginInit() { //------------------------------------------------------------- // In some older browsers do not implement these methods. @@ -7,9 +8,9 @@ function pluginInit() { // But this plugin needs them. // That's why if the browser does not have it, implement it. //------------------------------------------------------------- - if (typeof Array.prototype.forEach !== "function") { - (function() { - Array.prototype.forEach = function(fn, thisArg) { + if (typeof Array.prototype.forEach !== 'function') { + (function () { + Array.prototype.forEach = function (fn, thisArg) { thisArg = thisArg || this; for (var i = 0; i < this.length; i++) { fn.call(thisArg, this[i], i, this); @@ -17,9 +18,9 @@ function pluginInit() { }; })(); } - if (typeof Array.prototype.filter !== "function") { - (function() { - Array.prototype.filter = function(fn, thisArg) { + if (typeof Array.prototype.filter !== 'function') { + (function () { + Array.prototype.filter = function (fn, thisArg) { thisArg = thisArg || this; var results = []; for (var i = 0; i < this.length; i++) { @@ -31,9 +32,9 @@ function pluginInit() { }; })(); } - if (typeof Array.prototype.map !== "function") { - (function() { - Array.prototype.map = function(fn, thisArg) { + if (typeof Array.prototype.map !== 'function') { + (function () { + Array.prototype.map = function (fn, thisArg) { thisArg = thisArg || this; var results = []; for (var i = 0; i < this.length; i++) { @@ -51,14 +52,14 @@ function pluginInit() { var viewportTag = null; var metaTags = document.getElementsByTagName('meta'); for (var i = 0; i < metaTags.length; i++) { - if (metaTags[i].getAttribute('name') === "viewport") { - viewportTag = metaTags[i]; - break; - } + if (metaTags[i].getAttribute('name') === 'viewport') { + viewportTag = metaTags[i]; + break; + } } if (!viewportTag) { - viewportTag = document.createElement("meta"); - viewportTag.setAttribute('name', 'viewport'); + viewportTag = document.createElement('meta'); + viewportTag.setAttribute('name', 'viewport'); } var viewportTagContent = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'; @@ -84,52 +85,49 @@ function pluginInit() { // Update viewport tag attribute viewportTag.setAttribute('content', viewportTagContent); - /***************************************************************************** * Prevent background, background-color, background-image properties *****************************************************************************/ - var cssAdjuster = document.createElement("style"); - cssAdjuster.setAttribute("type", "text/css"); + var cssAdjuster = document.createElement('style'); + cssAdjuster.setAttribute('type', 'text/css'); cssAdjuster.innerText = [ - "html, body, ._gmaps_cdv_ {", - " background-image: url() !important;", - " background: rgba(0,0,0,0) url() !important;", - " background-color: rgba(0,0,0,0) !important;", - "}", - "._gmaps_cdv_ .nav-decor {", - " background-color: rgba(0,0,0,0) !important;", - " background: rgba(0,0,0,0) !important;", - " display:none !important;", - "}", - ".framework7-root .page-previous {", - " display:none !important;", - "}" - ].join(""); + 'html, body, ._gmaps_cdv_ {', + ' background-image: url() !important;', + ' background: rgba(0,0,0,0) url() !important;', + ' background-color: rgba(0,0,0,0) !important;', + '}', + '._gmaps_cdv_ .nav-decor {', + ' background-color: rgba(0,0,0,0) !important;', + ' background: rgba(0,0,0,0) !important;', + ' display:none !important;', + '}', + '.framework7-root .page-previous {', + ' display:none !important;', + '}' + ].join(''); document.head.appendChild(cssAdjuster); - // I guess no longer necessary this code at 2018/March // //---------------------------------------------- // // Set transparent mandatory for older browser // // http://stackoverflow.com/a/3485654/697856 // //---------------------------------------------- // if(document.body){ - // document.body.style.backgroundColor = "rgba(0,0,0,0)"; + // document.body.style.backgroundColor = 'rgba(0,0,0,0)'; // //document.body.style.display='none'; // document.body.offsetHeight; // //document.body.style.display=''; // } - - //-------------------------------------------- // Hook the backbutton of Android action //-------------------------------------------- var anotherBackbuttonHandler = null; + function onBackButton(e) { // Check DOM tree for new page - cordova.fireDocumentEvent("plugin_touch", { + cordova.fireDocumentEvent('plugin_touch', { force: true }); @@ -142,13 +140,13 @@ function pluginInit() { } } - document.addEventListener("backbutton", onBackButton); + document.addEventListener('backbutton', onBackButton); var _org_addEventListener = document.addEventListener; var _org_removeEventListener = document.removeEventListener; - document.addEventListener = function(eventName, callback) { + document.addEventListener = function (eventName, callback) { var args = Array.prototype.slice.call(arguments, 0); - if (eventName.toLowerCase() !== "backbutton") { + if (eventName.toLowerCase() !== 'backbutton') { _org_addEventListener.apply(this, args); return; } @@ -156,9 +154,9 @@ function pluginInit() { anotherBackbuttonHandler = callback; } }; - document.removeEventListener = function(eventName, callback) { + document.removeEventListener = function (eventName, callback) { var args = Array.prototype.slice.call(arguments, 0); - if (eventName.toLowerCase() !== "backbutton") { + if (eventName.toLowerCase() !== 'backbutton') { _org_removeEventListener.apply(this, args); return; } diff --git a/www/poly.js b/www/poly.js index 05344a9d9..26d882e2f 100644 --- a/www/poly.js +++ b/www/poly.js @@ -2,8 +2,8 @@ var LatLngBounds = require('./LatLngBounds'), BaseArrayClass = require('./BaseArrayClass'); function containsLocation(latLng, path) { - if ("lat" in latLng === false || - "lng" in latLng === false) { + if ('lat' in latLng === false || + 'lng' in latLng === false) { return false; } if (path instanceof BaseArrayClass) { @@ -61,14 +61,14 @@ function containsLocation(latLng, path) { } function isLocationOnEdge(latLng, path) { - if ("lat" in latLng === false || - "lng" in latLng === false) { + if ('lat' in latLng === false || + 'lng' in latLng === false) { return false; } var Sx, Sy; var p0, p1; - var point = {"lat": latLng.lat, "lng": latLng.lng}; + var point = {'lat': latLng.lat, 'lng': latLng.lng}; if (path instanceof BaseArrayClass) { path = path.getArray(); diff --git a/www/spherical.js b/www/spherical.js index ca390ebb7..04a08c93e 100644 --- a/www/spherical.js +++ b/www/spherical.js @@ -13,7 +13,7 @@ var EARTH_RADIUS = 6371009; * @param m The modulus. */ function mod(x, m) { - return ((x % m) + m) % m; + return ((x % m) + m) % m; } /** * Wraps the given value into the inclusive-exclusive interval between min and max. @@ -22,7 +22,7 @@ function mod(x, m) { * @param max The maximum. */ function wrap(n, min, max) { - return (n >= min && n < max) ? n : (mod(n - min, max - min) + min); + return (n >= min && n < max) ? n : (mod(n - min, max - min) + min); } /** @@ -30,8 +30,8 @@ function wrap(n, min, max) { * hav(x) == (1 - cos(x)) / 2 == sin(x / 2)^2. */ function hav(x) { - var sinHalf = Math.sin(x * 0.5); - return sinHalf * sinHalf; + var sinHalf = Math.sin(x * 0.5); + return sinHalf * sinHalf; } /** @@ -40,21 +40,21 @@ function hav(x) { * The argument must be in [0, 1], and the result is positive. */ function arcHav(x) { - return 2 * Math.asin(Math.sqrt(x)); + return 2 * Math.asin(Math.sqrt(x)); } /** * Returns hav() of distance from (lat1, lng1) to (lat2, lng2) on the unit sphere. */ function havDistance(lat1, lat2, dLng) { - return hav(lat1 - lat2) + hav(dLng) * Math.cos(lat1) * Math.cos(lat2); + return hav(lat1 - lat2) + hav(dLng) * Math.cos(lat1) * Math.cos(lat2); } /** * Returns distance on the unit sphere; the arguments are in radians. */ function distanceRadians(lat1, lng1, lat2, lng2) { - return arcHav(havDistance(lat1, lat2, lng1 - lng2)); + return arcHav(havDistance(lat1, lat2, lng1 - lng2)); } /** @@ -62,74 +62,73 @@ function distanceRadians(lat1, lng1, lat2, lng2) { * on the unit sphere. */ function computeAngleBetween(from, to) { - return distanceRadians(toRadians(from.lat), toRadians(from.lng), - toRadians(to.lat), toRadians(to.lng)); + return distanceRadians(toRadians(from.lat), toRadians(from.lng), + toRadians(to.lat), toRadians(to.lng)); } /** * Returns the distance between two LatLngs, in meters. */ function computeDistanceBetween(from, to) { - return computeAngleBetween(from, to) * EARTH_RADIUS; + return computeAngleBetween(from, to) * EARTH_RADIUS; } /** * Returns the distance between two LatLngs, in meters. */ function computeOffset(from, distance, heading) { - distance /= EARTH_RADIUS; - heading = toRadians(heading); + distance /= EARTH_RADIUS; + heading = toRadians(heading); - // http://williams.best.vwh.net/avform.htm#LL - var fromLat = toRadians(from.lat); - var fromLng = toRadians(from.lng); - var cosDistance = Math.cos(distance); - var sinDistance = Math.sin(distance); - var sinFromLat = Math.sin(fromLat); - var cosFromLat = Math.cos(fromLat); - var sinLat = cosDistance * sinFromLat + sinDistance * cosFromLat * Math.cos(heading); - var dLng = Math.atan2( - sinDistance * cosFromLat * Math.sin(heading), - cosDistance - sinFromLat * sinLat); - return new LatLng(toDegrees(Math.asin(sinLat)), toDegrees(fromLng + dLng)); + // http://williams.best.vwh.net/avform.htm#LL + var fromLat = toRadians(from.lat); + var fromLng = toRadians(from.lng); + var cosDistance = Math.cos(distance); + var sinDistance = Math.sin(distance); + var sinFromLat = Math.sin(fromLat); + var cosFromLat = Math.cos(fromLat); + var sinLat = cosDistance * sinFromLat + sinDistance * cosFromLat * Math.cos(heading); + var dLng = Math.atan2( + sinDistance * cosFromLat * Math.sin(heading), + cosDistance - sinFromLat * sinLat); + return new LatLng(toDegrees(Math.asin(sinLat)), toDegrees(fromLng + dLng)); } - function toRadians(d) { - return d * Math.PI / 180; + return d * Math.PI / 180; } function toDegrees(r) { - return r * 180 / Math.PI; + return r * 180 / Math.PI; } /* * Returns the signed area of a closed path on a sphere of given radius. */ function computeSignedArea(path) { - radius = EARTH_RADIUS; - path = common.convertToPositionArray(path); + var radius = EARTH_RADIUS; + path = common.convertToPositionArray(path); - var size = path.length; - if (size < 3) { - return 0; - } - var total = 0; + var size = path.length; + if (size < 3) { + return 0; + } + var total = 0; - var prev = path[size - 1]; - var prevTanLat = Math.tan((Math.PI / 2 - toRadians(prev.lat)) / 2); - var prevLng = toRadians(prev.lng); + var prev = path[size - 1]; + var prevTanLat = Math.tan((Math.PI / 2 - toRadians(prev.lat)) / 2); + var prevLng = toRadians(prev.lng); - // For each edge, accumulate the signed area of the triangle formed by the North Pole - // and that edge ("polar triangle"). - path.forEach(function(position) { - var tanLat = Math.tan((Math.PI / 2 - toRadians(position.lat)) / 2); - var lng = toRadians(position.lng); - total += polarTriangleArea(tanLat, lng, prevTanLat, prevLng); - prevTanLat = tanLat; - prevLng = lng; - }); - return total * (radius * radius); + // For each edge, accumulate the signed area of the triangle formed by the North Pole + // and that edge ("polar triangle"). + path.forEach(function (position) { + var tanLat = Math.tan((Math.PI / 2 - toRadians(position.lat)) / 2); + var lng = toRadians(position.lng); + total += polarTriangleArea(tanLat, lng, prevTanLat, prevLng); + prevTanLat = tanLat; + prevLng = lng; + }); + return total * (radius * radius); } /* @@ -141,12 +140,13 @@ function computeSignedArea(path) { */ function polarTriangleArea(tan1, lng1, tan2, lng2) { - var deltaLng = lng1 - lng2; - var t = tan1 * tan2; - return 2 * Math.atan2(t * Math.sin(deltaLng), 1 + t * Math.cos(deltaLng)); + var deltaLng = lng1 - lng2; + var t = tan1 * tan2; + return 2 * Math.atan2(t * Math.sin(deltaLng), 1 + t * Math.cos(deltaLng)); } + function computeArea(path) { - return Math.abs(computeSignedArea(path)); + return Math.abs(computeSignedArea(path)); } /** @@ -155,16 +155,16 @@ function computeArea(path) { * @return The heading in degrees clockwise from north. */ function computeHeading(from, to) { - // http://williams.best.vwh.net/avform.htm#Crs - var fromLat = toRadians(from.lat); - var fromLng = toRadians(from.lng); - var toLat = toRadians(to.lat); - var toLng = toRadians(to.lng); - var dLng = toLng - fromLng; - var heading = Math.atan2( - Math.sin(dLng) * Math.cos(toLat), - Math.cos(fromLat) * Math.sin(toLat) - Math.sin(fromLat) * Math.cos(toLat) * Math.cos(dLng)); - return wrap(toDegrees(heading), -180, 180); + // http://williams.best.vwh.net/avform.htm#Crs + var fromLat = toRadians(from.lat); + var fromLng = toRadians(from.lng); + var toLat = toRadians(to.lat); + var toLng = toRadians(to.lng); + var dLng = toLng - fromLng; + var heading = Math.atan2( + Math.sin(dLng) * Math.cos(toLat), + Math.cos(fromLat) * Math.sin(toLat) - Math.sin(fromLat) * Math.cos(toLat) * Math.cos(dLng)); + return wrap(toDegrees(heading), -180, 180); } /** @@ -177,41 +177,40 @@ function computeHeading(from, to) { * @param heading The heading in degrees clockwise from north. */ function computeOffsetOrigin(to, distance, heading) { - heading = toRadians(heading); - distance /= EARTH_RADIUS; - // http://lists.maptools.org/pipermail/proj/2008-October/003939.html - var n1 = Math.cos(distance); - var n2 = Math.sin(distance) * Math.cos(heading); - var n3 = Math.sin(distance) * Math.sin(heading); - var n4 = Math.sin(toRadians(to.lat)); - // There are two solutions for b. b = n2 * n4 +/- sqrt(), one solution results - // in the latitude outside the [-90, 90] range. We first try one solution and - // back off to the other if we are outside that range. - var n12 = n1 * n1; - var discriminant = n2 * n2 * n12 + n12 * n12 - n12 * n4 * n4; - if (discriminant < 0) { - // No real solution which would make sense in LatLng-space. - return null; - } - var b = n2 * n4 + Math.sqrt(discriminant); + heading = toRadians(heading); + distance /= EARTH_RADIUS; + // http://lists.maptools.org/pipermail/proj/2008-October/003939.html + var n1 = Math.cos(distance); + var n2 = Math.sin(distance) * Math.cos(heading); + var n3 = Math.sin(distance) * Math.sin(heading); + var n4 = Math.sin(toRadians(to.lat)); + // There are two solutions for b. b = n2 * n4 +/- sqrt(), one solution results + // in the latitude outside the [-90, 90] range. We first try one solution and + // back off to the other if we are outside that range. + var n12 = n1 * n1; + var discriminant = n2 * n2 * n12 + n12 * n12 - n12 * n4 * n4; + if (discriminant < 0) { + // No real solution which would make sense in LatLng-space. + return null; + } + var b = n2 * n4 + Math.sqrt(discriminant); + b /= n1 * n1 + n2 * n2; + var a = (n4 - n2 * b) / n1; + var fromLatRadians = Math.atan2(a, b); + if (fromLatRadians < -Math.PI / 2 || fromLatRadians > Math.PI / 2) { + b = n2 * n4 - Math.sqrt(discriminant); b /= n1 * n1 + n2 * n2; - var a = (n4 - n2 * b) / n1; - var fromLatRadians = Math.atan2(a, b); - if (fromLatRadians < - Math.PI / 2 || fromLatRadians > Math.PI / 2) { - b = n2 * n4 - Math.sqrt(discriminant); - b /= n1 * n1 + n2 * n2; - fromLatRadians = Math.atan2(a, b); - } - if (fromLatRadians < - Math.PI / 2 || fromLatRadians > Math.PI / 2) { - // No solution which would make sense in LatLng-space. - return null; - } - var fromLngRadians = toRadians(to.lng) - - Math.atan2(n3, n1 * Math.cos(fromLatRadians) - n2 * Math.sin(fromLatRadians)); - return new LatLng(toDegrees(fromLatRadians), toDegrees(fromLngRadians)); + fromLatRadians = Math.atan2(a, b); + } + if (fromLatRadians < -Math.PI / 2 || fromLatRadians > Math.PI / 2) { + // No solution which would make sense in LatLng-space. + return null; + } + var fromLngRadians = toRadians(to.lng) - + Math.atan2(n3, n1 * Math.cos(fromLatRadians) - n2 * Math.sin(fromLatRadians)); + return new LatLng(toDegrees(fromLatRadians), toDegrees(fromLngRadians)); } - /** * Returns the LatLng which lies the given fraction of the way between the * origin LatLng and the destination LatLng. @@ -221,62 +220,62 @@ function computeOffsetOrigin(to, distance, heading) { * @return The interpolated LatLng. */ function interpolate(from, to, fraction) { - // http://en.wikipedia.org/wiki/Slerp - var fromLat = toRadians(from.lat); - var fromLng = toRadians(from.lng); - var toLat = toRadians(to.lat); - var toLng = toRadians(to.lng); - var cosFromLat = Math.cos(fromLat); - var cosToLat = Math.cos(toLat); + // http://en.wikipedia.org/wiki/Slerp + var fromLat = toRadians(from.lat); + var fromLng = toRadians(from.lng); + var toLat = toRadians(to.lat); + var toLng = toRadians(to.lng); + var cosFromLat = Math.cos(fromLat); + var cosToLat = Math.cos(toLat); - // Computes Spherical interpolation coefficients. - var angle = computeAngleBetween(from, to); - var sinAngle = Math.sin(angle); - if (sinAngle < 1E-6) { - return from; - } - var a = Math.sin((1 - fraction) * angle) / sinAngle; - var b = Math.sin(fraction * angle) / sinAngle; + // Computes Spherical interpolation coefficients. + var angle = computeAngleBetween(from, to); + var sinAngle = Math.sin(angle); + if (sinAngle < 1E-6) { + return from; + } + var a = Math.sin((1 - fraction) * angle) / sinAngle; + var b = Math.sin(fraction * angle) / sinAngle; - // Converts from polar to vector and interpolate. - var x = a * cosFromLat * Math.cos(fromLng) + b * cosToLat * Math.cos(toLng); - var y = a * cosFromLat * Math.sin(fromLng) + b * cosToLat * Math.sin(toLng); - var z = a * Math.sin(fromLat) + b * Math.sin(toLat); + // Converts from polar to vector and interpolate. + var x = a * cosFromLat * Math.cos(fromLng) + b * cosToLat * Math.cos(toLng); + var y = a * cosFromLat * Math.sin(fromLng) + b * cosToLat * Math.sin(toLng); + var z = a * Math.sin(fromLat) + b * Math.sin(toLat); - // Converts interpolated vector back to polar. - var lat = Math.atan2(z, Math.sqrt(x * x + y * y)); - var lng = Math.atan2(y, x); - return new LatLng(toDegrees(lat), toDegrees(lng)); + // Converts interpolated vector back to polar. + var lat = Math.atan2(z, Math.sqrt(x * x + y * y)); + var lng = Math.atan2(y, x); + return new LatLng(toDegrees(lat), toDegrees(lng)); } /** * Returns the length of the given path, in meters, on Earth. */ function computeLength(path) { - path = common.convertToPositionArray(path); - if (path.length < 2) { - return 0; - } - var length = 0; - var prev = path[0]; - var prevLat = toRadians(prev.lat); - var prevLng = toRadians(prev.lng); - path.forEach(function(point) { - var lat = toRadians(point.lat); - var lng = toRadians(point.lng); - length += distanceRadians(prevLat, prevLng, lat, lng); - prevLat = lat; - prevLng = lng; - }); - return length * EARTH_RADIUS; + path = common.convertToPositionArray(path); + if (path.length < 2) { + return 0; + } + var length = 0; + var prev = path[0]; + var prevLat = toRadians(prev.lat); + var prevLng = toRadians(prev.lng); + path.forEach(function (point) { + var lat = toRadians(point.lat); + var lng = toRadians(point.lng); + length += distanceRadians(prevLat, prevLng, lat, lng); + prevLat = lat; + prevLng = lng; + }); + return length * EARTH_RADIUS; } module.exports = { - computeDistanceBetween: computeDistanceBetween, - computeOffset: computeOffset, - computeOffsetOrigin: computeOffsetOrigin, - computeArea: computeArea, - computeSignedArea: computeSignedArea, - computeHeading: computeHeading, - interpolate: interpolate, - computeLength: computeLength + computeDistanceBetween: computeDistanceBetween, + computeOffset: computeOffset, + computeOffsetOrigin: computeOffsetOrigin, + computeArea: computeArea, + computeSignedArea: computeSignedArea, + computeHeading: computeHeading, + interpolate: interpolate, + computeLength: computeLength };