I'm trying to use the html5 geolocation api with Meteor.
I'm using:
navigator.geolocation.getCurrentPosition(handle_geolocation_query); in my js but it doesn't seem to work - I think it may be related to the timer ( http://docs.meteor.com/#timers ) restrictions Meteor has. Any thoughts?
Thanks #lashleigh it was a loading problem
Here is the code that worked for me (I'm using Modernizr.js to detect geo-location)
if (Meteor.is_client) {
Session.set('loc','?');
//alert(Modernizr.geolocation);
function foundLocation(location) {
console.log(location);
Session.set('loc','lat: '+location.coords.latitude+', lan: '+ location.coords.longitude);
}
function noLocation() {
alert('no location');
}
Template.hello.greeting = function () {
var output;
if (Modernizr.geolocation) {
navigator.geolocation.getCurrentPosition(foundLocation, noLocation);
outpout = Session.get('loc');
}
return Session.get('loc');
};
}
Related
Usually in a plain javascript site, I can use the following script to reference google maps api and set the callback function with initMap.
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
What I observed is the initMap function in the plain javascript site is under the window scope, and it can be referenced in the script parameter settings - ?callback=initMap, but once I write a component in angular2 with a component method called initMap, the initMap will be under the scope of my component. Then the async loading script I set up in the index will not be able to catch my component initMap method.
Specifically, I 'd like to know how to achieve the same thing in Angular2?
PS: I know there is an angular2-google-maps component available in alpha via npm, but it currently is shipped with limited capability, so I 'd like to know how to load it in an easier way without using another component so I can just use google maps api to implement my project.
I see you don't want another component, but polymer has components that work well with google apis. I have angular2 code that uses the polymer youtube data api. I had help getting it setup. Here is the plunker that got me started. I think the hardpart is getting setup for that callback, I'm sure you can do it without polymer. The example shows the tricky part an angular service is used to hook everything up.
const url = 'https://apis.google.com/js/client.js?onload=__onGoogleLoaded'
export class GoogleAPI {
loadAPI: Promise<any>
constructor(){
this.loadAPI = new Promise((resolve) => {
window['__onGoogleLoaded'] = (ev) => {
console.log('gapi loaded')
resolve(window.gapi);
}
this.loadScript()
});
}
doSomethingGoogley(){
return this.loadAPI.then((gapi) => {
console.log(gapi);
});
}
loadScript(){
console.log('loading..')
let node = document.createElement('script');
node.src = url;
node.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(node);
}
}
I came across this while trying to develop a progressive web app, i.e. where there was a possibility of not being online. There was an error in the code examples: onload in the google maps script should be callback. So my modification of user2467174 led to
map-loader.service.ts
const url = 'http://maps.googleapis.com/maps/api/js?key=xxxxx&callback=__onGoogleLoaded';
#Injectable()
export class GoogleMapsLoader {
private static promise;
public static load() {
// First time 'load' is called?
if (!GoogleMapsLoader.promise) {
// Make promise to load
GoogleMapsLoader.promise = new Promise( resolve => {
// Set callback for when google maps is loaded.
window['__onGoogleLoaded'] = (ev) => {
resolve('google maps api loaded');
};
let node = document.createElement('script');
node.src = url;
node.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(node);
});
}
// Always return promise. When 'load' is called many times, the promise is already resolved.
return GoogleMapsLoader.promise;
}
}
And then I have a component with
import { GoogleMapsLoader } from './map/map-loader.service';
constructor() {
GoogleMapsLoader.load()
.then(res => {
console.log('GoogleMapsLoader.load.then', res);
this.mapReady = true;
})
And a template
<app-map *ngIf='mapReady'></app-map>
This way the map div is only put into the dom if online.
And then in the map.component.ts we can wait until the component is placed into the DOM before loading the map itself.
ngOnInit() {
if (typeof google !== 'undefined') {
console.log('MapComponent.ngOnInit');
this.loadMap();
}
}
Just in case you'd like to make it a static function, which always returns a promise, but only gets the api once.
const url = 'https://maps.googleapis.com/maps/api/js?callback=__onGoogleMapsLoaded&ey=YOUR_API_KEY';
export class GoogleMapsLoader {
private static promise;
public static load() {
// First time 'load' is called?
if (!GoogleMapsLoader.promise) {
// Make promise to load
GoogleMapsLoader.promise = new Promise((resolve) => {
// Set callback for when google maps is loaded.
window['__onGoogleMapsLoaded'] = (ev) => {
console.log('google maps api loaded');
resolve(window['google']['maps']);
};
// Add script tag to load google maps, which then triggers the callback, which resolves the promise with windows.google.maps.
console.log('loading..');
let node = document.createElement('script');
node.src = url;
node.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(node);
});
}
// Always return promise. When 'load' is called many times, the promise is already resolved.
return GoogleMapsLoader.promise;
}
}
This is how you can get the api in other scripts:
GoogleMapsLoader.load()
.then((_mapsApi) => {
debugger;
this.geocoder = new _mapsApi.Geocoder();
this.geocoderStatus = _mapsApi.GeocoderStatus;
});
This is what I'm currently using:
loadMapsScript(): Promise<void> {
return new Promise(resolve => {
if (document.querySelectorAll(`[src="${mapsScriptUrl}"]`).length) {
resolve();
} else {
document.body.appendChild(Object.assign(document.createElement('script'), {
type: 'text/javascript',
src: mapsScriptUrl,
onload: doMapInitLogic();
}));
}
});
}
See my more comprehensive instructions here
So I'm trying to have a function run when i click on an image. It works with a normal image, but i'm getting the images from a reddit JSON file. I need the images to resize separately and I can't figure out how. It's probably something simple, but i'm still new to coding, so any help would be great.
$.getJSON("http://www.reddit.com/r/pcmasterrace/.json?jsonp=?", function (data) {
$.each(data.data.children, function (i, item) {
IsValidImageUrl(item.data.url, function (url, isvalid) {
if (isvalid) {
$('<img/>').attr('src', item.data.url)
.appendTo('#images')
.width(500)
.onclick = function() {Resize()};
}
});
});
});
Is the function right?
function Resize() {
if (document.getElementById('<img/>').style.width === "500px") {
document.getElementById('<img/>').style.width = "1000px";
} else {
document.getElementById('<img/>').style.width = "500px";
}
}
I think the ('<img/>') might be wrong. I tested it with ('test') and it worked, so do i need it to be something different? It worked with my test function so the .click worked so i think it's trying to change the wrong thing.
onclick is a property of DOM elements, not jQuery objects. You should use the click() function to add a click handler.
.getJSON("http://www.reddit.com/r/pcmasterrace/.json?jsonp=?", function (data) {
$.each(data.data.children, function (i, item) {
IsValidImageUrl(item.data.url, function (url, isvalid) {
if (isvalid) {
$('<img/>').attr('src', item.data.url)
.appendTo('#images')
.width(500)
.click(function() {Resize(this)});
}
});
});
});
Your Resize function should take an argument telling it which image to change:
function Resize(image) {
if (image.style.width == "500px") {
image.style.width = "1000px";
} else {
image.style.width = "500px";
}
}
I'm wanting to take advantage of the google maps loader callback as demonstrated here:
https://developers.google.com/maps/documentation/javascript/examples/map-simple-async
I have a working example of doing this using AMD and promises. To load and consume the API:
require(["path/to/google-maps-api-v3"], function (api) {
api.then(function (googleMaps) {
// consume the api
});
});
Here's my module def which I'd prefer return google.maps after it's full loaded instead of a deferred:
define(["dojo/Deferred"], function (Deferred) {
var d = new Deferred();
dojoConfig["googleMapsReady"] = function () {
delete dojoConfig["googleMapsReady"];
d.resolve(google.maps);
}
require(["http://maps.google.com/maps/api/js?v=3&sensor=false&callback=dojoConfig.ipsx.config.googleMapsReady&"]);
return d;
});
But solution returns a promise instead of the fully initialized google.maps. I'd prefer it to appear like a regular AMD module but can't see how.
Create an AMD plugin. Here's the one I created based on JanMisker's example:
define(function () {
var cb ="_asyncApiLoaderCallback";
return {
load: function (param, req, loadCallback) {
if (!cb) return;
dojoConfig[cb] = function () {
delete dojoConfig[cb];
cb = null;
loadCallback(google.maps);
}
require([param + "&callback=dojoConfig." + cb]);
}
};
});
Usage example:
require(["plugins/async!//maps.google.com/maps/api/js?v=3&sensor=false"]);
I'm just learning angularJS (using angular-seed) and I need to load my site config from a JSON feed before the rest of the site loads.
Unfortunately, using $http or $resource doesn't return the feed in time for the rest of the app to load.
What is the correct way to force the app to load this data before the rest of the app?
You have to use the Controller.resolve method. Check out Misko's (one of the core Angular developer) answer https://stackoverflow.com/a/11972028/726711
Using the resolve method broke all my unit tests... I went with this way, where settings is a service.
$q.when(settings.loadConfig()).then(function () {
console.log( settings.versionedApiUrl );
});
Then, i check if we've already loaded settings to make sure we don't request more than once.
class settings {
loadConfig = ( ):angular.IPromise<any> => {
var deferred = this.q.defer();
if( this.settingsLoaded ){
deferred.resolve({})
return deferred.promise;
}
this.http({
url:'config.json'
}).then((result) => {
if( result.data ){
this.versionedApiUrl = result.data.versionedApiUrl;
this.apiServer = result.data.apiServer;
this.widgetServiceRoot = result.data.widgetServiceRoot;
this.settingsLoaded = true;
}
deferred.resolve({});
});
return deferred.promise;
}
}
I'm building a small web app in Flash. Is there a solution to get the geo-location of a user?
The easiest way is to interface with a JavaScript function.
In your HTML:
<script>
function getGEO()
{
// First check if your browser supports the geolocation API
if (navigator.geolocation)
{
//alert("HTML 5 is getting your location");
// Get the current position
navigator.geolocation.getCurrentPosition(function(position)
{
lat = position.coords.latitude
long = position.coords.longitude;
// Pass the coordinates to Flash
passGEOToSWF(lat, long);
});
} else {
//alert("Sorry... your browser does not support the HTML5 GeoLocation API");
}
}
function passGEOToSWF(lat,long)
{
//alert("HTML 5 is sending your location to Flash");
// Pass the coordinates to mySWF using ExternalInterface
document.getElementById("index").passGEOToSWF(lat,long);
}
</script>
Then, in your Application, once your map is ready, put this in a function:
//for getting a user's location
if (ExternalInterface.available)
{
//check if external interface is available
try
{
// add Callback for the passGEOToSWF Javascript function
ExternalInterface.addCallback("passGEOToSWF", onPassGEOToSWF);
}
catch (error:SecurityError)
{
// Alert the user of a SecurityError
}
catch (error:Error)
{
// Alert the user of an Error
}
}
Finally, have a private function ready to catch the callback.
private function onPassGEOToSWF(lat:*,long:*):void
{
userLoc = new LatLng(lat,long);
map.setCenter(userLoc);
}