diff --git a/.gitignore b/.gitignore index 0286574..1d87d49 100644 --- a/.gitignore +++ b/.gitignore @@ -19,12 +19,12 @@ npm-debug.log* .tmp/ .versions/ coverage/ -www/ +/www/ node_modules/ tmp/ temp/ platforms/ -plugins/ +/plugins/ plugins/android.json plugins/ios.json $RECYCLE.BIN/ diff --git a/docs/plugins/cordova-plugin-device/src/browser/DeviceProxy.js b/docs/plugins/cordova-plugin-device/src/browser/DeviceProxy.js new file mode 100644 index 0000000..a4998fe --- /dev/null +++ b/docs/plugins/cordova-plugin-device/src/browser/DeviceProxy.js @@ -0,0 +1,86 @@ +cordova.define("cordova-plugin-device.DeviceProxy", function(require, exports, module) { /* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +var browser = require('cordova/platform'); + +function getPlatform () { + return 'browser'; +} + +function getModel () { + return getBrowserInfo(true); +} + +function getVersion () { + return getBrowserInfo(false); +} + +function getBrowserInfo (getModel) { + var userAgent = navigator.userAgent; + var returnVal = ''; + var offset; + + if ((offset = userAgent.indexOf('Edge')) !== -1) { + returnVal = (getModel) ? 'Edge' : userAgent.substring(offset + 5); + } else if ((offset = userAgent.indexOf('Chrome')) !== -1) { + returnVal = (getModel) ? 'Chrome' : userAgent.substring(offset + 7); + } else if ((offset = userAgent.indexOf('Safari')) !== -1) { + if (getModel) { + returnVal = 'Safari'; + } else { + returnVal = userAgent.substring(offset + 7); + + if ((offset = userAgent.indexOf('Version')) !== -1) { + returnVal = userAgent.substring(offset + 8); + } + } + } else if ((offset = userAgent.indexOf('Firefox')) !== -1) { + returnVal = (getModel) ? 'Firefox' : userAgent.substring(offset + 8); + } else if ((offset = userAgent.indexOf('MSIE')) !== -1) { + returnVal = (getModel) ? 'MSIE' : userAgent.substring(offset + 5); + } else if ((offset = userAgent.indexOf('Trident')) !== -1) { + returnVal = (getModel) ? 'MSIE' : '11'; + } + + if ((offset = returnVal.indexOf(';')) !== -1 || (offset = returnVal.indexOf(' ')) !== -1) { + returnVal = returnVal.substring(0, offset); + } + + return returnVal; +} + +module.exports = { + getDeviceInfo: function (success, error) { + setTimeout(function () { + success({ + cordova: browser.cordovaVersion, + platform: getPlatform(), + model: getModel(), + version: getVersion(), + uuid: null, + isVirtual: false + }); + }, 0); + } +}; + +require('cordova/exec/proxy').add('Device', module.exports); + +}); diff --git a/docs/plugins/cordova-plugin-device/www/device.js b/docs/plugins/cordova-plugin-device/www/device.js new file mode 100644 index 0000000..059351d --- /dev/null +++ b/docs/plugins/cordova-plugin-device/www/device.js @@ -0,0 +1,85 @@ +cordova.define("cordova-plugin-device.device", function(require, exports, module) { /* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +var argscheck = require('cordova/argscheck'); +var channel = require('cordova/channel'); +var utils = require('cordova/utils'); +var exec = require('cordova/exec'); +var cordova = require('cordova'); + +channel.createSticky('onCordovaInfoReady'); +// Tell cordova channel to wait on the CordovaInfoReady event +channel.waitForInitialization('onCordovaInfoReady'); + +/** + * This represents the mobile device, and provides properties for inspecting the model, version, UUID of the + * phone, etc. + * @constructor + */ +function Device () { + this.available = false; + this.platform = null; + this.version = null; + this.uuid = null; + this.cordova = null; + this.model = null; + this.manufacturer = null; + this.isVirtual = null; + this.serial = null; + + var me = this; + + channel.onCordovaReady.subscribe(function () { + me.getInfo(function (info) { + // ignoring info.cordova returning from native, we should use value from cordova.version defined in cordova.js + // TODO: CB-5105 native implementations should not return info.cordova + var buildLabel = cordova.version; + me.available = true; + me.platform = info.platform; + me.version = info.version; + me.uuid = info.uuid; + me.cordova = buildLabel; + me.model = info.model; + me.isVirtual = info.isVirtual; + me.manufacturer = info.manufacturer || 'unknown'; + me.serial = info.serial || 'unknown'; + channel.onCordovaInfoReady.fire(); + }, function (e) { + me.available = false; + utils.alert('[ERROR] Error initializing Cordova: ' + e); + }); + }); +} + +/** + * Get device info + * + * @param {Function} successCallback The function to call when the heading data is available + * @param {Function} errorCallback The function to call when there is an error getting the heading data. (OPTIONAL) + */ +Device.prototype.getInfo = function (successCallback, errorCallback) { + argscheck.checkArgs('fF', 'Device.getInfo', arguments); + exec(successCallback, errorCallback, 'Device', 'getDeviceInfo', []); +}; + +module.exports = new Device(); + +}); diff --git a/docs/plugins/cordova-plugin-googlemaps/src/browser/CordovaGoogleMaps.js b/docs/plugins/cordova-plugin-googlemaps/src/browser/CordovaGoogleMaps.js new file mode 100644 index 0000000..da9823d --- /dev/null +++ b/docs/plugins/cordova-plugin-googlemaps/src/browser/CordovaGoogleMaps.js @@ -0,0 +1,183 @@ +cordova.define("cordova-plugin-googlemaps.CordovaGoogleMaps", function(require, exports, module) { + + +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'); + +var MAPS = {}; + +var API_LOADED_STATUS = 0; // 0: not loaded, 1: loading, 2: completed + +document.addEventListener('load_googlemaps', function() { + var envOptions = Environment._getEnv(); + var API_KEY_FOR_BROWSER; + if (envOptions) { + if (location.protocol === 'https:') { + API_KEY_FOR_BROWSER = envOptions.API_KEY_FOR_BROWSER_RELEASE; + } else { + API_KEY_FOR_BROWSER = envOptions.API_KEY_FOR_BROWSER_DEBUG; + } + } + API_LOADED_STATUS = 1; + + var secureStripeScript = document.createElement('script'); + if (API_KEY_FOR_BROWSER) { + secureStripeScript.setAttribute('src','https://maps.googleapis.com/maps/api/js?key=' + API_KEY_FOR_BROWSER); + } else { + // for development only + secureStripeScript.setAttribute('src','https://maps.googleapis.com/maps/api/js'); + } + 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'); + } + }); + }); + + 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'); + } + }); + }); + + document.getElementsByTagName('head')[0].appendChild(secureStripeScript); + +}, { + once: true +}); + +var stub = function(onSuccess) { + onSuccess(); +}; + +var CordovaGoogleMaps = { + resume: stub, + pause: stub, + getMap: function(onSuccess, onError, args) { + // memory cleanup + var mapIDs = Object.keys(MAPS); + mapIDs.forEach(function(mapId) { + var mapDivId = document.querySelector('[__pluginmapid=\'' + mapId + '\']'); + if (!mapDivId) { + if (MAPS[mapDivId]) { + MAPS[mapDivId].destroy(); + } + MAPS[mapDivId] = undefined; + delete MAPS[mapDivId]; + } + }); + + var meta = args[0], + mapId = meta.__pgmId; + args[0] = mapId; + args.unshift(this); + + var pluginMap = new (PluginMap.bind.apply(PluginMap, args)); + MAPS[mapId] = pluginMap; + var dummyObj = {}; + var keys = Object.getOwnPropertyNames(PluginMap.prototype).filter(function (p) { + return typeof PluginMap.prototype[p] === 'function'; + }); + keys.forEach(function(key) { + dummyObj[key] = pluginMap[key].bind(pluginMap); + }); + require('cordova/exec/proxy').add(mapId, dummyObj); + + pluginMap.one(event.MAP_READY, onSuccess); + pluginMap.one('load_error', onError); + + // Does this app already load the google maps library? + 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; + } + }, + removeMap: function(onSuccess, onError, args) { + var mapId = args[0]; + var pluginMap = MAPS[mapId]; + if (pluginMap) { + var map = pluginMap.get('map'); + google.maps.event.clearInstanceListeners(map); + var mapDiv = map.getDiv(); + if (mapDiv) { + mapDiv.parentNode.removeChild(mapDiv); + pluginMap.set('map', undefined); + } + } + pluginMap.destroy(); + pluginMap = null; + MAPS[mapId] = undefined; + delete MAPS[mapId]; + onSuccess(); + }, + + getPanorama: function(onSuccess, onError, args) { + // memory cleanup + var mapIDs = Object.keys(MAPS); + mapIDs.forEach(function(mapId) { + var mapDivId = document.querySelector('[__pluginmapid=\'' + mapId + '\']'); + if (!mapDivId) { + if (MAPS[mapDivId]) { + MAPS[mapDivId].destroy(); + } + MAPS[mapDivId] = undefined; + delete MAPS[mapDivId]; + } + }); + + var meta = args[0], + mapId = meta.__pgmId; + args[0] = mapId; + args.unshift(this); + + var pluginStreetView = new (PluginStreetViewPanorama.bind.apply(PluginStreetViewPanorama, args)); + MAPS[mapId] = pluginStreetView; + var dummyObj = {}; + var keys = Object.getOwnPropertyNames(PluginStreetViewPanorama.prototype).filter(function (p) { + return typeof PluginStreetViewPanorama.prototype[p] === 'function'; + }); + keys.forEach(function(key) { + dummyObj[key] = pluginStreetView[key].bind(pluginStreetView); + }); + require('cordova/exec/proxy').add(mapId, dummyObj); + + pluginStreetView.one(event.PANORAMA_READY, onSuccess); + pluginStreetView.one('load_error', onError); + + // Does this app already load the google maps library? + 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; + } + }, +}; + +require('cordova/exec/proxy').add('CordovaGoogleMaps', CordovaGoogleMaps); + +}); diff --git a/docs/plugins/cordova-plugin-googlemaps/src/browser/PluginCircle.js b/docs/plugins/cordova-plugin-googlemaps/src/browser/PluginCircle.js new file mode 100644 index 0000000..70e6138 --- /dev/null +++ b/docs/plugins/cordova-plugin-googlemaps/src/browser/PluginCircle.js @@ -0,0 +1,201 @@ +cordova.define("cordova-plugin-googlemaps.PluginCircle", function(require, exports, module) { + + +var utils = require('cordova/utils'), + event = require('cordova-plugin-googlemaps.event'), + BaseClass = require('cordova-plugin-googlemaps.BaseClass'); + +function PluginCircle(pluginMap) { + var self = this; + BaseClass.apply(self); + Object.defineProperty(self, 'pluginMap', { + value: pluginMap, + writable: false + }); +} + +utils.extend(PluginCircle, BaseClass); + +PluginCircle.prototype._create = function(onSuccess, onError, args) { + var self = this, + map = self.pluginMap.get('map'), + circleId = 'circle_' + args[2], + pluginOptions = args[1]; + + var circleOpts = { + 'overlayId': circleId, + 'map': map + }; + + circleOpts.center = pluginOptions.center; + circleOpts.radius = pluginOptions.radius; + + if (Array.isArray(pluginOptions.strokeColor)) { + circleOpts.strokeColor = 'rgb(' + pluginOptions.strokeColor[0] + ',' + pluginOptions.strokeColor[1] + ',' + pluginOptions.strokeColor[2] + ')'; + circleOpts.strokeOpacity = pluginOptions.strokeColor[3] / 256; + } + if (Array.isArray(pluginOptions.fillColor)) { + circleOpts.fillColor = 'rgb(' + pluginOptions.fillColor[0] + ',' + pluginOptions.fillColor[1] + ',' + pluginOptions.fillColor[2] + ')'; + circleOpts.fillOpacity = pluginOptions.fillColor[3] / 256; + } + if ('width' in pluginOptions) { + circleOpts.strokeWeight = pluginOptions.width; + } + if ('zIndex' in pluginOptions) { + circleOpts.zIndex = pluginOptions.zIndex; + } + if ('visible' in pluginOptions) { + circleOpts.visible = pluginOptions.visible; + } + if ('clickable' in pluginOptions) { + circleOpts.clickable = pluginOptions.clickable; + } + + var circle = new google.maps.Circle(circleOpts); + circle.addListener('click', function(polyMouseEvt) { + self._onCircleEvent.call(self, circle, polyMouseEvt); + }); + + self.pluginMap.objects[circleId] = circle; + + onSuccess({ + '__pgmId': circleId + }); +}; + +PluginCircle.prototype.setCenter = function(onSuccess, onError, args) { + var self = this; + var overlayId = args[0]; + var lat = args[1]; + var lng = args[2]; + var circle = self.pluginMap.objects[overlayId]; + if (circle) { + circle.setCenter(new google.maps.LatLng(lat, lng)); + } + onSuccess(); +}; + +PluginCircle.prototype.setFillColor = function(onSuccess, onError, args) { + var self = this; + var overlayId = args[0]; + var fillColor = args[1]; + var circle = self.pluginMap.objects[overlayId]; + if (circle) { + + if (Array.isArray(fillColor)) { + circle.setOptions({ + 'fillColor': 'rgb(' + fillColor[0] + ',' + fillColor[1] + ',' + fillColor[2] + ')', + 'fillOpacity': fillColor[3] / 256 + }); + } + } + onSuccess(); +}; + +PluginCircle.prototype.setStrokeColor = function(onSuccess, onError, args) { + var self = this; + var overlayId = args[0]; + var strokeColor = args[1]; + var circle = self.pluginMap.objects[overlayId]; + if (circle) { + + if (Array.isArray(strokeColor)) { + circle.setOptions({ + 'strokeColor': 'rgb(' + strokeColor[0] + ',' + strokeColor[1] + ',' + strokeColor[2] + ')', + 'strokeOpacity': strokeColor[3] / 256 + }); + } + } + onSuccess(); +}; + +PluginCircle.prototype.setStrokeWidth = function(onSuccess, onError, args) { + var self = this; + var overlayId = args[0]; + var width = args[1]; + var circle = self.pluginMap.objects[overlayId]; + if (circle) { + circle.setOptions({ + 'strokeWeight': width + }); + } + onSuccess(); +}; + +PluginCircle.prototype.setRadius = function(onSuccess, onError, args) { + var self = this; + var overlayId = args[0]; + var radius = args[1]; + var circle = self.pluginMap.objects[overlayId]; + if (circle) { + circle.setRadius(radius); + } + onSuccess(); +}; + +PluginCircle.prototype.setZIndex = function(onSuccess, onError, args) { + var self = this; + var overlayId = args[0]; + var zIndex = args[1]; + var circle = self.pluginMap.objects[overlayId]; + if (circle) { + circle.setOptions({ + 'zIndex': zIndex + }); + } + onSuccess(); +}; + +PluginCircle.prototype.setVisible = function(onSuccess, onError, args) { + var self = this; + var overlayId = args[0]; + var visible = args[1]; + var circle = self.pluginMap.objects[overlayId]; + if (circle) { + circle.setVisible(visible === true); + } + onSuccess(); +}; + +PluginCircle.prototype.setClickable = function(onSuccess, onError, args) { + var self = this; + var overlayId = args[0]; + var clickable = args[1]; + var circle = self.pluginMap.objects[overlayId]; + if (circle) { + circle.setOptions({ + 'clickable': clickable === true + }); + } + onSuccess(); +}; + +PluginCircle.prototype.remove = function(onSuccess, onError, args) { + var self = this; + var overlayId = args[0]; + var circle = self.pluginMap.objects[overlayId]; + if (circle) { + google.maps.event.clearInstanceListeners(circle); + circle.setMap(null); + circle = undefined; + self.pluginMap.objects[overlayId] = undefined; + delete self.pluginMap.objects[overlayId]; + } + onSuccess(); +}; + +PluginCircle.prototype._onCircleEvent = function(circle, polyMouseEvt) { + var self = this, + mapId = self.pluginMap.__pgmId; + if (mapId in plugin.google.maps) { + plugin.google.maps[mapId]({ + 'evtName': event.CIRCLE_CLICK, + 'callback': '_onOverlayEvent', + 'args': [circle.overlayId, new plugin.google.maps.LatLng(polyMouseEvt.latLng.lat(), polyMouseEvt.latLng.lng())] + }); + } + +}; +module.exports = PluginCircle; + +}); diff --git a/docs/plugins/cordova-plugin-googlemaps/src/browser/PluginEnvironment.js b/docs/plugins/cordova-plugin-googlemaps/src/browser/PluginEnvironment.js new file mode 100644 index 0000000..53919bf --- /dev/null +++ b/docs/plugins/cordova-plugin-googlemaps/src/browser/PluginEnvironment.js @@ -0,0 +1,33 @@ +cordova.define("cordova-plugin-googlemaps.PluginEnvironment", function(require, exports, module) { +var envOptions = {}; + +module.exports = { + 'isAvailable': function(onSuccess) { + onSuccess(); + }, + 'setBackGroundColor': function(onSuccess) { + // stub + onSuccess(); + }, + '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.'); + }, + 'setEnv': function(onSuccess, onError, args) { + var options = args[0]; + var keys = Object.keys(options); + keys.forEach(function(key) { + envOptions[key] = options[key]; + }); + onSuccess(); + }, + '_getEnv': function() { + // internal method + return envOptions; + } +}; + + +require('cordova/exec/proxy').add('PluginEnvironment', module.exports); + +}); diff --git a/docs/plugins/cordova-plugin-googlemaps/src/browser/PluginGeocoder.js b/docs/plugins/cordova-plugin-googlemaps/src/browser/PluginGeocoder.js new file mode 100644 index 0000000..a8c7953 --- /dev/null +++ b/docs/plugins/cordova-plugin-googlemaps/src/browser/PluginGeocoder.js @@ -0,0 +1,181 @@ +cordova.define("cordova-plugin-googlemaps.PluginGeocoder", function(require, exports, module) { + +var BaseArrayClass = require('cordova-plugin-googlemaps.BaseArrayClass'); + +var geocoder = null; +var lastRequestTime = 0; +var QUEUE = new BaseArrayClass(); +QUEUE.on('insert_at', function() { + if (QUEUE.getLength() === 1) { + this.trigger('next'); + } +}); +QUEUE.one('insert_at', function() { + geocoder = new google.maps.Geocoder(); + this.trigger('next'); +}); +QUEUE.on('next', function() { + var self = QUEUE; + if (!geocoder || self._executing || QUEUE.getLength() === 0) { + return; + } + if (Date.now() - lastRequestTime < 300) { + setTimeout(function() { + self.trigger('next'); + }, 300 + Math.floor(Math.random() * 200)); + return; + } + lastRequestTime = Date.now(); + self._executing = true; + + 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; + } + + var pluginResults = results.map(function(geocoderResult) { + var result = { + 'position': { + 'lat': geocoderResult.geometry.location.lat(), + 'lng': geocoderResult.geometry.location.lng() + }, + extra: { + lines: [] + } + }; + if (geocoderResult.place_id) { + result.extra.place_id = geocoderResult.place_id; + } + if (geocoderResult.plus_code) { + result.extra.plus_code = geocoderResult.plus_code; + } + if (geocoderResult.types) { + result.extra.types = geocoderResult.types; + } + + var administrative_area = []; + var sublocality_area = []; + geocoderResult.address_components.forEach(function(addrComp) { + result.extra.lines.push(addrComp.long_name); + 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) { + addrComp.types.forEach(function(type) { + 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) { + addrComp.types.forEach(function(type) { + 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) { + result.country = addrComp.long_name; + result.countryCode = addrComp.short_name; + } + if (!result.postalCode && addrComp.types.indexOf('postal_code') > -1) { + result.postalCode = addrComp.long_name; + } + if (!result.postalCode && addrComp.types.indexOf('postal_code') > -1) { + result.postalCode = addrComp.long_name; + } + 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(','); + } + if (sublocality_area.length > 0) { + result.subLocality = sublocality_area.join(','); + } + //result.extra = geocoderResult.address_components; // for debug + + return result; + }); + + self._executing = false; + cmd.onSuccess({ + 'idx': cmd.pluginRequest.idx, + 'results': pluginResults + }); + + // Insert delay to prevent the OVER_QUERY_LIMIT error. + var delay = 300 + Math.floor(Math.random() * 200); + setTimeout(function() { + self._executing = false; + self.trigger('next'); + }, delay); + }); +}); + +module.exports = { + 'geocode': function(onSuccess, onError, args) { + var request = args[0]; + var geocoderRequest = {}; + + if (!request.position && request.address) { + //--------------------- + // Geocoding + //--------------------- + if (request.bounds && Array.isArray(request.bounds)) { + var bounds = new google.maps.LatLngBounds(); + request.bounds.forEach(function(position) { + bounds.extend(position); + }); + geocoderRequest.bounds = bounds; + } + geocoderRequest.address = request.address; + } + if (request.position && !request.address) { + geocoderRequest.location = request.position; + } + QUEUE.push({ + 'geocoderRequest': geocoderRequest, + 'pluginRequest': request, + 'onSuccess': onSuccess, + 'onError': onError + }); + } +}; + + +require('cordova/exec/proxy').add('PluginGeocoder', module.exports); + +}); diff --git a/docs/plugins/cordova-plugin-googlemaps/src/browser/PluginGroundOverlay.js b/docs/plugins/cordova-plugin-googlemaps/src/browser/PluginGroundOverlay.js new file mode 100644 index 0000000..74f885f --- /dev/null +++ b/docs/plugins/cordova-plugin-googlemaps/src/browser/PluginGroundOverlay.js @@ -0,0 +1,414 @@ +cordova.define("cordova-plugin-googlemaps.PluginGroundOverlay", function(require, exports, module) { + + +var utils = require('cordova/utils'), + event = require('cordova-plugin-googlemaps.event'), + BaseClass = require('cordova-plugin-googlemaps.BaseClass'), + Spherical = require('cordova-plugin-googlemaps.spherical'), + LatLng = require('cordova-plugin-googlemaps.LatLng'); + +function PluginGroundOverlay(pluginMap) { + var self = this; + BaseClass.apply(self); + Object.defineProperty(self, 'pluginMap', { + value: pluginMap, + writable: false + }); +} + +utils.extend(PluginGroundOverlay, BaseClass); + +PluginGroundOverlay.prototype._create = function(onSuccess, onError, args) { + var self = this, + map = self.pluginMap.get('map'), + groundoverlayId = 'groundoverlay_' + args[2], + pluginOptions = args[1]; + + var groundoverlayOpts = { + 'overlayId': groundoverlayId, + 'map': map + }; + + var bounds = new google.maps.LatLngBounds(); + pluginOptions.bounds.forEach(function(latLng) { + bounds.extend(latLng); + }); + + if ('bearing' in pluginOptions) { + groundoverlayOpts.bearing = pluginOptions.bearing; + } + if ('zIndex' in pluginOptions) { + groundoverlayOpts.zIndex = pluginOptions.zIndex; + } + if ('opacity' in pluginOptions) { + groundoverlayOpts.opacity = pluginOptions.opacity; + } + if ('visible' in pluginOptions) { + groundoverlayOpts.visible = pluginOptions.visible; + } + if ('clickable' in pluginOptions) { + groundoverlayOpts.clickable = pluginOptions.clickable; + } + + var groundoverlay = newGroundOverlay(pluginOptions.url, bounds, groundoverlayOpts); + groundoverlay.addListener('click', function(polyMouseEvt) { + self._onGroundOverlayEvent.call(self, groundoverlay, polyMouseEvt); + }); + + self.pluginMap.objects[groundoverlayId] = groundoverlay; + self.pluginMap.objects['groundoverlay_property_' + groundoverlayId] = pluginOptions; + + + onSuccess({ + '__pgmId': groundoverlayId + }); +}; +PluginGroundOverlay.prototype.setImage = function(onSuccess, onError, args) { + var self = this, + overlayId = args[0], + url = args[1], + groundoverlay = self.pluginMap.objects[overlayId]; + + if (groundoverlay) { + groundoverlay.setImage(url); + } + + onSuccess(); +}; + +PluginGroundOverlay.prototype.setBearing = function(onSuccess, onError, args) { + var self = this; + var overlayId = args[0]; + var groundOverlay = self.pluginMap.objects[overlayId]; + if (groundOverlay) { + groundOverlay.setBearing(args[1]); + } + onSuccess(); +}; + +PluginGroundOverlay.prototype.setOpacity = function(onSuccess, onError, args) { + var self = this; + var overlayId = args[0]; + var groundOverlay = self.pluginMap.objects[overlayId]; + if (groundOverlay) { + groundOverlay.setOpacity(args[1]); + } + onSuccess(); +}; + +PluginGroundOverlay.prototype.setBounds = function(onSuccess, onError, args) { + var self = this; + var overlayId = args[0]; + var groundOverlay = self.pluginMap.objects[overlayId]; + if (groundOverlay) { + + var points = args[1]; + var bounds = new google.maps.LatLngBounds(); + points.forEach(function(latLng) { + bounds.extend(latLng); + }); + groundOverlay.setBounds(bounds); + } + onSuccess(); +}; + +PluginGroundOverlay.prototype.setZIndex = function(onSuccess, onError, args) { + var self = this; + var overlayId = args[0]; + var zIndex = args[1]; + var groundOverlay = self.pluginMap.objects[overlayId]; + if (groundOverlay) { + groundOverlay.setZIndex(zIndex); + } + onSuccess(); +}; + +PluginGroundOverlay.prototype.setClickable = function(onSuccess, onError, args) { + var self = this; + var overlayId = args[0]; + var groundOverlay = self.pluginMap.objects[overlayId]; + if (groundOverlay) { + groundOverlay.setClickable(args[1]); + } + onSuccess(); +}; +PluginGroundOverlay.prototype.setVisible = function(onSuccess, onError, args) { + var self = this; + var overlayId = args[0]; + var groundOverlay = self.pluginMap.objects[overlayId]; + if (groundOverlay) { + groundOverlay.setVisible(args[1]); + } + onSuccess(); +}; + +PluginGroundOverlay.prototype.remove = function(onSuccess, onError, args) { + var self = this; + var overlayId = args[0]; + var groundOverlay = self.pluginMap.objects[overlayId]; + if (groundOverlay) { + google.maps.event.clearInstanceListeners(groundOverlay); + groundOverlay.setMap(null); + groundOverlay.remove(); + groundOverlay = undefined; + self.pluginMap.objects[overlayId] = undefined; + delete self.pluginMap.objects[overlayId]; + delete self.pluginMap.objects['groundoverlay_property_' + overlayId]; + } + onSuccess(); +}; + +PluginGroundOverlay.prototype._onGroundOverlayEvent = function(groundoverlay, mouseEvt) { + var self = this, + mapId = self.pluginMap.__pgmId; + if (mapId in plugin.google.maps) { + plugin.google.maps[mapId]({ + 'evtName': event.GROUND_OVERLAY_CLICK, + 'callback': '_onOverlayEvent', + 'args': [groundoverlay.overlayId, new LatLng(mouseEvt.latLng.lat(), mouseEvt.latLng.lng())] + }); + } + +}; +module.exports = PluginGroundOverlay; + +function newGroundOverlay(url, bounds, options) { + + // https://github.com/apache/cordova-js/blob/c75e8059114255d1dbae1ede398e6626708ee9f3/src/common/utils.js#L167 + if (CustomGroundOverlay.__super__ !== google.maps.OverlayView.prototype) { + var key, defined = {}; + for (key in CustomGroundOverlay.prototype) { + defined[key] = CustomGroundOverlay.prototype[key]; + } + utils.extend(CustomGroundOverlay, google.maps.OverlayView); + for (key in defined) { + CustomGroundOverlay.prototype[key] = defined[key]; + } + } + + return new CustomGroundOverlay(url, bounds, options); +} + +function CustomGroundOverlay(url, bounds, options) { + google.maps.OverlayView.apply(this); + var self = this; + + //------------------------------------------------------------ + // Create an img element, then put it on map as GroundOverlay + //------------------------------------------------------------ + 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.src = self.get('url'); + }); + + var path = new google.maps.MVCArray([ + new google.maps.LatLng(0, 0), + new google.maps.LatLng(0, 0), + new google.maps.LatLng(0, 0), + new google.maps.LatLng(0, 0) + ]); + self.set('path', path); + + self.addListener('bearing_changed', self.updateVertixes); + self.addListener('bounds_changed', self.updateVertixes); + self.addListener('opacity_changed', function() { + img.style.opacity = self.get('opacity'); + }); + + //--------------------------------------------------------- + // Create a transparent rectangle above the groundOverlay, + // then catch click event + //--------------------------------------------------------- + var touchPolygon = new google.maps.Polygon({ + 'map': options.map, + 'paths': path, + 'clickable': true, + 'fillColor': 'red', + 'fillOpacity': 0, + 'strokeOpacity': 0, + 'zIndex': options.zIndex || 0 + }); + self.addListener('visible_changed', function() { + img.style.visibility = self.get('visible') ? 'visible' : 'hidden'; + touchPolygon.setVisible(self.get('visible')); + }); + + self.addListener('zIndex_changed', function() { + touchPolygon.setOptions({ + 'zIndex': self.get('zIndex') + }); + img.style.zIndex = self.get('zIndex'); + }); + + touchPolygon.addListener('click', function(evt) { + if (self.get('clickable')) { + google.maps.event.trigger(self, 'click', { + 'latLng': evt. latLng + }); + } + }); + self.set('touchPolygon', touchPolygon); + + var markers = []; + for (var i = 0; i < 4; i++) { + markers.push(new google.maps.Marker({ + 'position': {'lat': 0, 'lng': 0}, + 'map': options.map + })); + } + self.set('markers', markers); + + + //--------------------------------------------------------- + // Apply option values + //--------------------------------------------------------- + for (var key in options) { + self.set(key, options[key]); + } + self.set('bounds', bounds); +} +CustomGroundOverlay.prototype.updateVertixes = function() { + var self = this; + var degree = self.get('bearing') || 0; + + // Get center + var bounds = self.get('bounds'); + if (!bounds) { + return; + } + var center = bounds.getCenter(), + centerPos = { + 'lat': center.lat(), + 'lng': center.lng() + }; + + // original NorthEast + var orgNE = bounds.getNorthEast(), + orgSW = bounds.getSouthWest(), + orgNEpos = { + 'lat': orgNE.lat(), + 'lng': orgNE.lng() + }; + var orgDrgreeNE = Spherical.computeHeading(centerPos, orgNEpos); + var orgDrgreeSE = Spherical.computeHeading(centerPos, { + 'lat': orgSW.lat(), + 'lng': orgNE.lng() + }); + + var distanceCenter2NE = Spherical.computeDistanceBetween(orgNEpos, centerPos); + // new NorthEast + var newNE = Spherical.computeOffsetOrigin(centerPos, distanceCenter2NE, degree + orgDrgreeNE); + + // new SourthEast + var newSE = Spherical.computeOffsetOrigin(centerPos, distanceCenter2NE, degree + orgDrgreeSE); + // new SourthWest + var newSW = Spherical.computeOffsetOrigin(centerPos, distanceCenter2NE, degree + orgDrgreeNE + 180); + // new SouthEast + var newNW = Spherical.computeOffsetOrigin(centerPos, distanceCenter2NE, degree + orgDrgreeSE + 180); + + // Caclulate bounds + var path = self.get('path'); + path.setAt(0, new google.maps.LatLng(newNE.lat, newNE.lng)); + path.setAt(1, new google.maps.LatLng(newSE.lat, newSE.lng)); + path.setAt(2, new google.maps.LatLng(newSW.lat, newSW.lng)); + path.setAt(3, new google.maps.LatLng(newNW.lat, newNW.lng)); + + self.draw(); +}; + +CustomGroundOverlay.prototype.remove = function() { + var self = this; + self.set('img', undefined); + google.maps.event.clearInstanceListeners(self); + google.maps.event.clearInstanceListeners(self.get('touchPolygon')); +}; + +CustomGroundOverlay.prototype.setClickable = function(clickable) { + var self = this; + self.set('clickable', clickable); +}; + +CustomGroundOverlay.prototype.setOpacity = function(opacity) { + var self = this; + self.get('img').style.opacity = opacity; +}; + +CustomGroundOverlay.prototype.setBearing = function(bearing) { + var self = this; + self.set('bearing', bearing); +}; + +CustomGroundOverlay.prototype.setBounds = function(bounds) { + var self = this; + self.set('bounds', bounds); +}; + +CustomGroundOverlay.prototype.setOpacity = function(opacity) { + var self = this; + self.set('opacity', opacity); +}; + +CustomGroundOverlay.prototype.setZIndex = function(zIndex) { + var self = this; + self.set('zIndex', zIndex); +}; + +CustomGroundOverlay.prototype.setVisible = function(visible) { + var self = this; + self.set('visible', visible); +}; + +CustomGroundOverlay.prototype.setImage = function(url) { + var self = this; + self.set('url', url); +}; + +CustomGroundOverlay.prototype.getBounds = function() { + var self = this; + return new google.maps.LatLngBounds( + self.get('sw'), self.get('ne') + ); +}; +CustomGroundOverlay.prototype.draw = function() { + var self = this, + projection = self.getProjection(); + if (!projection) { + return; + } + var bounds = self.get('bounds'), + 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.transform = 'rotate(' + self.get('bearing') + 'deg)'; + img.style.WebkitTransform = 'rotate(' + self.get('bearing') + 'deg)'; + img.style.MozTransform = 'rotate(' + self.get('bearing') + 'deg)'; +}; + +CustomGroundOverlay.prototype.onAdd = function() { + var self = this; + self.set('mapPane', self.getPanes().mapPane); + self.getPanes().mapPane.appendChild(self.get('img')); +}; + +CustomGroundOverlay.prototype.onRemove = function() { + var self = this; + self.get('mapPane').removeChild(self.get('img')); + google.maps.event.clearInstanceListeners(self.get('img')); +}; + +}); diff --git a/docs/plugins/cordova-plugin-googlemaps/src/browser/PluginKmlOverlay.js b/docs/plugins/cordova-plugin-googlemaps/src/browser/PluginKmlOverlay.js new file mode 100644 index 0000000..9a1e762 --- /dev/null +++ b/docs/plugins/cordova-plugin-googlemaps/src/browser/PluginKmlOverlay.js @@ -0,0 +1,542 @@ +cordova.define("cordova-plugin-googlemaps.PluginKmlOverlay", function(require, exports, module) { + +/* eslint no-useless-escape: off */ + +var InlineWorker = require('cordova-plugin-googlemaps.InlineWorker'); + +function PluginKmlOverlay() { + // stub +} + +PluginKmlOverlay.prototype._create = function(onSuccess, onError, args) { + var pluginOptions = args[1]; + + if (!/^https?:/.test(location.protocol)) { + return onError('KmlOverlay is only available on http: or https: protocols.'); + } + + //------------------------------------- + // Parse the xml file using WebWorker + //------------------------------------- + var worker = new InlineWorker(loadKml); + worker.onmessage = function(evt) { + //console.log('host message', evt.data); + worker.terminate(); + onSuccess(evt.data); + }; + worker.onerror = onError; + var link = document.createElement('a'); + link.href = pluginOptions.url; + var url = link.protocol+'//'+link.host+link.pathname+link.search; + worker.postMessage({ + 'url': url + }); +}; + +module.exports = PluginKmlOverlay; + +function loadKml(self) { + + // code: https://stackoverflow.com/q/32912732/697856 + var createCORSRequest = function(method, url, asynch) { + var xhr = new XMLHttpRequest(); + 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 window.XDomainRequest != 'undefined') { + // XDomainRequest for IE. + xhr = new window.XDomainRequest(); + xhr.open(method, url, asynch); + } else { + // CORS not supported. + xhr = null; + } + return xhr; + }; + + + //--------------------------------------- + // modified fromXML (xml parser) + //--------------------------------------- + var fromXML = (function() { + // fromXML + // https://github.com/kawanet/from-xml + // + // The MIT License (MIT) + // + // Copyright (c) 2016 Yusuke Kawasaki + // + // Permission is hereby granted, free of charge, to any person obtaining a copy + // of this software and associated documentation files (the "Software"), to deal + // in the Software without restriction, including without limitation the rights + // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + // copies of the Software, and to permit persons to whom the Software is + // furnished to do so, subject to the following conditions: + // + // The above copyright notice and this permission notice shall be included in all + // copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + // SOFTWARE. + + /** + * The fromXML() method parses an XML string, constructing the JavaScript + * value or object described by the string. + * + * @function fromXML + * @param text {String} The string to parse as XML + * @param [reviver] {Function} If a function, prescribes how the value + * originally produced by parsing is transformed, before being returned. + * @returns {Object} + */ + + var UNESCAPE = { + '&': '&', + '<': '<', + '>': '>', + ''': '\'', + '"': '"' + }; + + 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 length = list.length; + + // root element + var root = {f: []}; + var elem = root; + + // dom tree stack + var stack = []; + + for (var i = 0; i < length;) { + // text node + var str = list[i++]; + if (str) appendText(str); + + // child node + var tag = list[i++]; + if (tag) parseNode(tag); + } + + return root; + + function parseNode(tag) { + var tagLength = tag.length; + var firstChar = tag[0]; + if (firstChar === '/') { + // close tag + var closed = tag.replace(/^\/|[\s\/].*$/g, '').toLowerCase(); + while (stack.length) { + var tagName = elem.n && elem.n.toLowerCase(); + elem = stack.pop(); + if (tagName === closed) break; + } + // } 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) === ']]') { + // CDATA section + appendText(tag.substr(8, tagLength - 10)); + } else { + // comment + appendChild({n: '!', r: tag.substr(1)}); + } + } else { + var child = openTag(tag); + appendChild(child); + if (tag[tagLength - 1] === '/') { + child.c = 1; // emptyTag + } else { + stack.push(elem); // openTag + elem = child; + } + } + } + + function appendChild(child) { + elem.f.push(child); + } + + function appendText(str) { + str = removeSpaces(str); + if (str) appendChild(unescapeXML(str)); + } + } + + function openTag(tag) { + var elem = {f: []}; + tag = tag.replace(/\s*\/?$/, ''); + var pos = tag.search(/[\s='"\/]/); + if (pos < 0) { + elem.n = tag; + } else { + elem.n = tag.substr(0, pos); + elem.t = tag.substr(pos); + } + return elem; + } + + function parseAttribute(elem, reviver) { + if (!elem.t) return; + var list = elem.t.split(/([^\s='"]+(?:\s*=\s*(?:'[\S\s]*?'|"[\S\s]*?"|[^\s'"]*))?)/); + var attributes = {}; + + list.forEach(function(str) { + var val; + str = removeSpaces(str); + if (!str) return; + + var pos = str.indexOf('='); + if (pos < 0) { + // bare attribute + val = null; + } else { + // attribute key/value pair + 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 === '"')) { + val = val.substr(1, val.length - 2); + } + + val = unescapeXML(val); + } + if (reviver) { + val = reviver(str, val); + } + addAttribute(attributes, str, val); + }); + + return attributes; + } + + function removeSpaces(str) { + 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 (code > -1) return String.fromCharCode(code); + } + return UNESCAPE[str] || str; + }); + } + + function toObject(elem, reviver) { + // + // var raw = elem.r; + // if (raw) return raw; + + var attributes = parseAttribute(elem, reviver); + var object; + var childList = elem.f; + var childLength = childList && childList.length || 0; + + if (attributes || childLength > 1) { + // merge attributes and child nodes + if (typeof attributes === 'object') { + object = attributes; + object.line=198; + } else { + object = {}; + } + object.tagName = elem.n; + childList.forEach(function(child) { + if ('string' === typeof child) { + addObject(object, CHILD_NODE_KEY, child); + } else { + addObject(object, child.n, toObject(child, reviver)); + } + }); + } else if (childLength) { + // the node has single child node but no attribute + var child = childList[0]; + if ('string' === typeof child) { + object = { + 'tagName': elem.n, + 'value': child, + 'line': 215 + }; + } else { + object = toObject(child, reviver); + if (child.n) { + object = { + 'tagName': elem.n, + 'value': { + 'children': [object] + }, + 'line': 227 + }; + } + } + } else { + // the node has no attribute nor child node + object = { + 'tagName': elem.n, + 'value': '', + 'line': 233 + }; + } + + if (reviver) { + object = reviver(elem.n || '', object); + } + + return object; + } + + function addAttribute(object, key, val) { + if ('undefined' === typeof val) return; + object.attributes = object.attributes || {}; + object.attributes[key] = val; + } + function addObject(object, key, val) { + if ('undefined' === typeof val) return; + object.value = object.value || {}; + object.value.children = object.value.children || []; + if (typeof val === 'object' && val.tagName) { + object.value.children.push(val); + } else { + object.value.children.push({ + 'tagName': key, + 'value': val, + 'line': 258 + }); + } + } + + return function(text, reviver) { + text = text.replace(/<\?xml[^>]+>/i, ''); + var xmlTree = parseXML(text); + var result = toObject(xmlTree, reviver); + result.tagName = 'document'; + return result; + }; + })(); + + //--------------------------------------- + // KmlParserClass + //--------------------------------------- + function KmlParserClass() { + var _parser = this; + _parser.styleHolder = {}; + _parser.schemaHolder = {}; + + _parser.tagSwitchTables = { + 'styleurl': _parser._styleurl, + 'stylemap': _parser._style, + 'style': _parser._style, + 'schema': _parser._schema, + 'coordinates': _parser._coordinates + }; + } + + KmlParserClass.prototype.parseXml = function(rootElement) { + var _parser = this, + tagName = rootElement.tagName.toLowerCase(); + + + + var _proc = _parser.tagSwitchTables[tagName] || _parser._default; + //console.log("--->tagName = " + tagName, tagName in _parser.tagSwitchTables ? tagName : '_default'); + var result = _proc.call(_parser, rootElement); + result.tagName = tagName; + if (rootElement.attributes) { + var attrNames = Object.keys(rootElement.attributes); + attrNames.forEach(function(attrName) { + result[attrName] = rootElement.attributes[attrName]; + }); + } + return result; + }; + + KmlParserClass.prototype._styleurl = function(rootElement) { + return { + 'styleId': rootElement.value + }; + }; + + + KmlParserClass.prototype._style = function(rootElement) { + var _parser = this; + + // Generate a style id for the tag + var styleId = rootElement.attributes ? rootElement.attributes.id : null; + if (!styleId) { + styleId = '__' + Math.floor(Date.now() * Math.random()) + '__'; + } + var result = { + 'styleId': styleId + }; + + // Store style information into the styleHolder + var styles = {}; + var children = []; + if (rootElement.value.children) { + rootElement.value.children.forEach(function(childNode) { + var node = _parser.parseXml(childNode); + if (node.value) { + styles[node.tagName] = node.value; + } else { + children.push(node); + } + }); + if (children.length > 0) { + styles.children = children; + } + } + _parser.styleHolder[styleId] = styles; + return result; + }; + + KmlParserClass.prototype._schema = function(rootElement) { + var _parser = this; + var result = {}; + + // Generate a schema id for the tag + var schemaId = rootElement.attributes ? rootElement.attributes.id : null; + if (!schemaId) { + 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()) + '__'; + if (rootElement.value.children) { + var children = []; + rootElement.value.children.forEach(function(childNode) { + var node = _parser.parseXml(childNode); + if (node) { + children.push(node); + } + }); + if (children.length > 0) { + schema.children = children; + } + } + _parser.schemaHolder[schemaId] = schema; + + return result; + }; + + KmlParserClass.prototype._coordinates = function(rootElement) { + var result = {}; + var latLngList = []; + + var txt = rootElement.value; + 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(','); + latLngList.push({ + 'lat': parseFloat(tmpArry[1]), + 'lng': parseFloat(tmpArry[0]) + }); + } + }); + + result.coordinates = latLngList; + return result; + }; + + KmlParserClass.prototype._default = function(rootElement) { + var _parser = this, + result = {}; + + if (rootElement.value.children) { + var children = []; + rootElement.value.children.forEach(function(childNode) { + + var node = _parser.parseXml.call(_parser, childNode); + if (node) { + if ('styleId' in node) { + result.styleIDs = result.styleIDs || []; + result.styleIDs.push(node.styleId); + } else if (node.tagName !== 'schema') { + children.push(node); + } + } + + }); + result.children = children; + } else { + var value = rootElement.value; + if (/^-?[0-9]+$/.test(value)) { + result.value = parseInt(value, 10); + } else if (/^-?[0-9\.]+$/.test(value)) { + result.value = parseFloat(value, 10); + } else { + result.value = value; + } + } + return result; + }; + + + self.onmessage = function(evt) { + var params = evt.data; + //------------------------------------------ + // Load & parse kml file in WebWorker + //------------------------------------------ + (new Promise(function(resolve, reject) { + //----------------- + // Read XML file + //----------------- + var xhr = createCORSRequest('GET', params.url, true); + if (xhr) { + xhr.onreadystatechange = function() { + try { + if (xhr.readyState === 4) { + if (xhr.status === 200) { + resolve(xhr.responseText); + } else { + reject(xhr); + } + } + } catch (e) { + reject(e.description); + } + }; + xhr.send(); + } + })) + .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); + }); + + }; +} + +}); diff --git a/docs/plugins/cordova-plugin-googlemaps/src/browser/PluginLocationService.js b/docs/plugins/cordova-plugin-googlemaps/src/browser/PluginLocationService.js new file mode 100644 index 0000000..09f8ba1 --- /dev/null +++ b/docs/plugins/cordova-plugin-googlemaps/src/browser/PluginLocationService.js @@ -0,0 +1,61 @@ +cordova.define("cordova-plugin-googlemaps.PluginLocationService", function(require, exports, module) { +var LOCATION_ERROR = { + '1': 'service_denied', + '2': 'not_available', + '3': 'timeout' +}; + +module.exports = { + 'hasPermission': function(onSuccess, onError) { + if (navigator.permissions) { + navigator.permissions.query({'name': 'geolocation'}) + .then(function(permission) { + onSuccess(permission.state === 'granted' ? 1 : 0); + }) + .catch(onError); + } else { + onError('Browser does not support this feature.'); + } + }, + 'getMyLocation': function(onSuccess, onError) { + + if (navigator.geolocation) { + navigator.geolocation.getCurrentPosition(function(position) { + onSuccess({ + 'latLng': { + 'lat': position.coords.latitude, + 'lng': position.coords.longitude + }, + 'elapsedRealtimeNanos': 0, + 'time': position.timestamp, + 'accuracy': position.coords.accuracy, + 'altitude': position.coords.altitude, + 'speed': position.coords.speed, + 'bearing': position.coords.heading, + 'provider': 'geolocationapi', + 'hashCode': 'dummy', + 'status': true + }); + }, function(error) { + onError({ + 'status': false, + 'error_code': LOCATION_ERROR[error.code], + 'error_message': error.message + }); + }, { + 'enableHighAccuracy': true + }); + } else { + onError({ + 'status': false, + 'error_code': 'not_available', + 'error_message': 'Since this device does not have any location provider, this app can not detect your location.' + }); + } + } +}; + + +require('cordova/exec/proxy').add('PluginLocationService', module.exports); + +}); diff --git a/docs/plugins/cordova-plugin-googlemaps/src/browser/PluginMap.js b/docs/plugins/cordova-plugin-googlemaps/src/browser/PluginMap.js new file mode 100644 index 0000000..b24d5de --- /dev/null +++ b/docs/plugins/cordova-plugin-googlemaps/src/browser/PluginMap.js @@ -0,0 +1,724 @@ +cordova.define("cordova-plugin-googlemaps.PluginMap", function(require, exports, module) { + + +var utils = require('cordova/utils'), + event = require('cordova-plugin-googlemaps.event'), + BaseClass = require('cordova-plugin-googlemaps.BaseClass'), + LatLng = require('cordova-plugin-googlemaps.LatLng'), + 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'; + +var LOCATION_ERROR = {}; +LOCATION_ERROR[1] = 'service_denied'; +LOCATION_ERROR[2] = 'not_available'; +LOCATION_ERROR[3] = 'cannot_detect'; +var LOCATION_ERROR_MSG = {}; +LOCATION_ERROR_MSG[1] = 'Location service is rejected by user.'; +LOCATION_ERROR_MSG[2] = 'Since this device does not have any location provider, this app can not detect your location.'; +LOCATION_ERROR_MSG[3] = 'Can not detect your location. Try again.'; + +function displayGrayMap(container) { + var gmErrorContent = document.querySelector('.gm-err-container'); + var gmnoprint = document.querySelector('.gmnoprint'); + if (!gmErrorContent && !gmnoprint) { + container.innerHTML = [ + '