Geolocation add to Collection2

Hey guys! This forums has been nothing but amazing and i’m so happy, that there’s so many who wants to help.

I’m trying to implement a geolocation to my site, where it should be able to track the users location and insert it into my collection2 MongoDB schema. I’ve used this guide:

It returns a map with my current location. How do i then save the location, let’s say “New York” or “Michigan” in my collection?

1 Like

Hi fillah,

Do you have aldeed:geocoder added? If so you can have this:

var geo = new GeoCoder({
  geocoderProvider: "google",
  httpAdapter: "https",
  apiKey: 'YOUR API KEY'
});

If you have, or can geolocate the lat/long of the user, then you can just do this:

var result = geo.reverse(<lat>,<long>);

That will return an array/object that looks like this:

[ { formattedAddress: <this was my address in string form>,
     latitude: <this was my lat>,
     longitude: <this was my long>,
     extra: 
      { googlePlaceId: <this was my google place id>,
        confidence: 1,
        premise: null,
        subpremise: null,
        neighborhood: null,
        establishment: null },
     administrativeLevels: 
      { level3long: <this was my township in Pennsylvania>,
        level3short: <this was also my township in Pennsylvania>,
        level2long: 'Chester County',
        level2short: 'Chester County',
        level1long: 'Pennsylvania',
        level1short: 'PA' },
     streetNumber: <this was my house number as string>,
     streetName: <this was the road I live on>,
     city: 'Landenberg',
     country: 'United States',
     countryCode: 'US',
    zipcode: '19350' } ]

Then you could grab the fields you want and add them to the user record. Hope this helps.

1 Like

Hey @jaclynn!

I’ve actually managed adding the map and location to my site with the tutorial above. How do i then grab a variable like LatLng and example print it out? :slight_smile:

Edit: And how do i get my Api key?

Are you geolocating the user yet? If so, you can have code like this:

  if(navigator.geolocation) {
    var geoSuccess = function(position) {
    console.log(position.coords.latitude);       //<---here
    console.log(position.coords.longitude);    //<---and here
    };
    var geoError = function(error) {
      console.log('Error occurred. Error code: ' + error.code);
    };
    var geoOptions = {
      timeout: 100 * 1000,
      maximumAge: 75000
    };
    
   }; 
   navigator.geolocation.getCurrentPosition(geoSuccess, geoError, geoOptions);

To get an API key (from Google) go to https://console.developers.google.com, sign in with your google dev account, choose the hamburger menu, then API manager. You will get a key and then add the appropriate services to it.

3 Likes

I tried using your code example and got my API key but returns me an error:

Can’t find variable: GeoCoder

Can’t seem to figure out how to fix it (i’m kinda new to Meteor). I have installed the package.

Where are you getting your error? If it’s in the browser:

Your geocoder code should be on server side. Your navigator code should be on client side. Then create your geo variable on the server side and hard code a lat/long into the reverse statement and console.log it to make sure it’s working. Any errors would appear in your server log (i.e. your terminal/shell/command). If it works, you could then pass the user’s location through a method.

If it’s in your server log (terminal), make sure you have the the package installed correctly (you can look in your .meteor/packages file, or run meteor list at the prompt). If it is, paste your server code here (without the API key).

1 Like

Ah i get it now and returns the Latitude and Longitude. You have to tell me how you made this work:

var result = geo.reverse( < lat>,< long>);

I can’t figure it out to return the array / object.

Btw, thank you so much for your time!

That code was in my server side code, and I just entered hard-coded lat/long to make sure my geocoder was working.

As for capturing the users’s location, say city/state, I did that in a Meteor method where the lat/long was passed through, I geo-reversed it and took the appropriate object keys out of the resulting object.

I’ll see if I can put together some code for you. It may not be elegant :slight_smile:

I have made the following files to my project:

Client (folder)
test.html
test.js

Server (folder)
publish.js

In my publish.js folder, i have the var geo = new geocoder with apikey and the other. In my test.js folder i got the rest of the code where it puts the lat and lng in console.log. Where do you then say, that it should be? :slight_smile:

Ok here you go…

In client/test.js do this:

Template.body.onCreated(function() {      //<--this could be some other condition
if(navigator.geolocation) {
    var geoSuccess = function(position) {
    lat = position.coords.latitude;       
    lng = position.coords.longitude;    
    Meteor.call('geoReverseMe', lat, lng, function(err, data) {
    if (err) console.log(err);                        
    console.log(data);        //<--this will spit it out in browser console
    });

    };
    var geoError = function(error) {
      console.log('Error occurred. Error code: ' + error.code);
    };
    var geoOptions = {
      timeout: 100 * 1000,
      maximumAge: 75000
    };
   }; 
   navigator.geolocation.getCurrentPosition(geoSuccess, geoError, geoOptions);
});

Then in server/publish.js:

var geo = new GeoCoder({
  geocoderProvider: "google",
  httpAdapter: "https",
  apiKey: 'Your API KEY'          //<--replace
});

Meteor.methods({
	'geoReverseMe':function(lat,lng){
		var result = geo.reverse(lat,lng);
		return result;          //<--this will return it but you could also add to user record instead
	}
});
1 Like

It returns me an error in terminal:

Exception while invoking method 'geoReverseMe' Error: Status is REQUEST_DENIED. Browser API keys cannot have referer restrictions when used with this API.

On the site it says Error: Internal server error [500] and Undefined

Go to your google dev console, hamburger menu, API manager, credentials. Is there anything here:

I’ve added localhost:3000, not sure if it has to be online and i can see “Browser key 1” with the API key, which i copy / pasted

Try removing it just to see if it works. You can lock it down later.

Maybe it’s just their service that’s bugging. Now i can’t get a new key, even when i try creating a new project. Oh well :expressionless:

No - don’t remove the key. Try leaving the referrer field blank.

It didn’t work either. Maybe it’s just me… Is it Google Maps JavaScript API?

Here are the APIs I have loaded. You don’t need all of these, but at least get the Geo* ones.

Just to make sure that i’m doing this right, what to pick here?

http://imgur.com/HeSg7F2

If you choose Browser and leave it empty, it will be sufficient to test your georeverse.

To lock it down, make another one and choose server, but you will need to know your workstation’s IP public address (http://www.whatismyip.com, for example)), which might change depending on who your provider is. Once your app is in production, you’ll have a static IP and you add that in the “Accept request from…” box. For now, make a couple keys. A browser key with no referrers that you can try on your workstation, and one with a server key that can be locked down to just your prod server when you deploy. Just keep them safe, regardless.

1 Like