Git Product home page Git Product logo

node-googlemaps's Introduction

Build Status

Google Maps API for Node.js

This library implements the following Google Maps APIs, and can be also used by Google Maps for Work users.

This library is NOT COMPATIBLE with tags < 1.0.0

If you want to migrate from a version older than 1.0.0 check the WIKI for instructions.

Installation

npm install googlemaps

What does it cover

Maps API Web Services:

Google Places API - NOT COMPLETED

Google Maps Image API

Usage

var publicConfig = {
  key: '<YOUR-KEY>',
  stagger_time:       1000, // for elevationPath
  encode_polylines:   false,
  secure:             true, // use https
  proxy:              'http://127.0.0.1:9999' // optional, set a proxy for HTTP requests
};
var gmAPI = new GoogleMapsAPI(publicConfig);

// or in case you are using Google Maps for Work
var enterpriseConfig = {
  google_client_id:   '<YOUR-CLIENT-ID>', // to use Google Maps for Work
  google_private_key: '<YOUR-PRIVATE-KEY>', // to use Google Maps for Work
  google_channel:     '<YOUR-CHANNEL>' // to use Google Maps for Work application usage tracking
  stagger_time:       1000, // for elevationPath
  encode_polylines:   false,
  secure:             true, // use https
  proxy:              'http://127.0.0.1:9999' // optional, set a proxy for HTTP requests
};
var gmAPI = new GoogleMapsAPI(enterpriseConfig);

// geocode API
var geocodeParams = {
  "address":    "121, Curtain Road, EC2A 3AD, London UK",
  "components": "components=country:GB",
  "bounds":     "55,-1|54,1",
  "language":   "en",
  "region":     "uk"
};

gmAPI.geocode(geocodeParams, function(err, result){
  console.log(result);
});

// reverse geocode API
var reverseGeocodeParams = {
  "latlng":        "51.1245,-0.0523",
  "result_type":   "postal_code",
  "language":      "en",
  "location_type": "APPROXIMATE"
};

gmAPI.reverseGeocode(reverseGeocodeParams, function(err, result){
  console.log(result);
});

Check out the unit tests for more APIs examples.

Static Maps

var gmAPI = new GoogleMapsAPI();
var params = {
  center: '444 W Main St Lock Haven PA',
  zoom: 15,
  size: '500x400',
  maptype: 'roadmap',
  markers: [
    {
      location: '300 W Main St Lock Haven, PA',
      label   : 'A',
      color   : 'green',
      shadow  : true
    },
    {
      location: '444 W Main St Lock Haven, PA',
      icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_icon&chld=cafe%7C996600'
    }
  ],
  style: [
    {
      feature: 'road',
      element: 'all',
      rules: {
        hue: '0x00ff00'
      }
    }
  ],
  path: [
    {
      color: '0x0000ff',
      weight: '5',
      points: [
        '41.139817,-77.454439',
        '41.138621,-77.451596'
      ]
    }
  ]
};
gmAPI.staticMap(params); // return static map URL
gmAPI.staticMap(params, function(err, binaryImage) {
  // fetch asynchronously the binary image
});

This example prints the URL for the Static Map image: "https://maps.googleapis.com/maps/api/staticmap?center=444%20W%20Main%20St%20Lock%20Haven%20PA&zoom=15&size=500x400&maptype=roadmap&markers=color%3Agreen%7Clabel%3AA%7Cshadow%3Atrue%7C300%20W%20Main%20St%20Lock%20Haven%2C%20PA&markers=icon%3Ahttp%3A%2F%2Fchart.apis.google.com%2Fchart%3Fchst%3Dd_map_pin_icon%26chld%3Dcafe%257C996600%7C444%20W%20Main%20St%20Lock%20Haven%2C%20PA&path=weight%3A5%7Ccolor%3A0x0000ff%7Cenc%3A%7BbbzFfyvwMnFwP&style=feature%3Aroad%7Celement%3Aall%7Chue%3A0x00ff00"

By giving gm.staticMap an optional callback, you can retreive the static map PNG data:

You will get a map like:

Some Map

For custom markers using the icon parameter, a little-known scale parameter is also available that makes it possible to use high-resolution custom images on devices with retina displays. Set it to 2 and use it together with a @2x http-only image URL (Google's API does not support custom marker images served over https), such as:

{
  location: '999 Example Road, Earth',
  icon: 'http://example.com/path/to/[email protected]',
  scale: 2
}

Credits to this answer on SO.

Street view

var gmAPI = new GoogleMapsAPI();
var params = {
  location: '51.507868,-0.087689',
  size: '1200x1600',
  heading: 108.4,
  pitch: 7,
  fov: 40
};
var result = gmAPI.streetView(params);

London - Tower Bridge from London Bridge

Further examples

Please refer to the code, tests and the Google Maps API docs for further usage information.

Contributions

Criticism/Suggestions/Patches/PullRequests are welcome.

Original contributors list

evnm duncanm sugendran JoshSmith grobot regality spatical

v1.0.0 maintener

moshen fabriziomoscon

Contributions and new issues are welcome!

node-googlemaps's People

Contributors

aemkei avatar brandonwamboldt avatar evansiroky avatar evnm avatar fabriziomoscon avatar felix avatar grobot avatar jacoscaz avatar jettcalleja avatar joshsmith avatar kodextor avatar liorsion avatar lostintime avatar marsup avatar moshen avatar neilljordan avatar onthestairs avatar regality avatar sayotuke avatar spatical avatar themadbug avatar valyard avatar yujinlim avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-googlemaps's Issues

case sensitive for 'mode' argument for the directions service

I tried to pass a parameter to set the 'mode' argument in the functions for 'directions'. It didn't work. I didn't know what was wrong. After fighting with for some time, I realized that the argument doesn't work with Caps..
In the web page of the API, this has been used. Where I think DRIVING is an enum, which explains why it's capitalized.
I think it's a good idea to make it case-insensitive. For starters like myself, we could just use how it's in the official documentation of the api.
travelMode: google.maps.TravelMode.DRIVING

Case:
Used(my argument)->Result(In the response)
mode = 'WALKING'->"travel_mode":"DRIVING"
mode = 'walking'->"travel_mode":"WALKING"

Proxy doc or example?

hi,
does the proxy let to avoid the max usage limit?
is there any example please?
thanks

Order of response values is different than the client side google maps api

I noticed this while doing geocoding. It looks like you've implemented these functions to have the first parameter be the potential error value and the second parameter be the results, but the google maps api shows this format:
geocoder.geocode( { 'address': address}, function(results, status) { ... });
While noting this example, it also doesn't look like you allow an object for the address, only an address string itself.
I was thinking it would be nice to have these formats identical, or at the very least, more substantially documented. I think this is a great module so far.

Sample waypoint to use in the directions service

I have been trying to use directions service with waypoints, but wasn't able to. Could someone please help me out with a sample waypoints array using location coordinates to pass to the directions().

StreetView Nearby

In this package has been implemented the function getPanoramaByLocation with callback..???

I don't understand the parameters sequence :-(

I would like to get this, for search nearest streetview by location

var astorPlace = new google.maps.LatLng(40.729884, -73.990988);
var webService = new google.maps.StreetViewService();  
/**Check in a perimeter of 50 meters**/ 
var checkaround = 50;
/** checkNearestStreetView is a valid callback function **/

webService.getPanoramaByLocation(astorPlace,checkaround ,checkNearestStreetView);

function checkNearestStreetView(panoData){
    if(panoData){
        if(panoData.location){
            if(panoData.location.latLng){
                /**Well done you can use a nearest existing street view coordinates**/
            }
        }
    }
    /** Else do something... **/
}

Places API

When I run

"gm.places(options.latlng, "50000", googleKey, this.callback, "true", "bar". null, null, null);"

I only get a generated url returned rather than a JSON object.

create package.json file for npm

it would be good if you packaged this up for npm (the node package manager).

let me know if you have any questions on how to do this, i would be glad to assist :-)

Static map - can only generate a single style

Hi,

1.0.1

Params with a single style object:

var params = {
    center: '44.9545,-93.3365',
    zoom: 10,
    size: '640x640',
    scale: 2,
    maptype: 'roadmap',
    style: [
        {
            feature: 'all',
            rules: {
                invert_lightness: true,
                hue: '0x57574e'
            }
        }
    ]
}

Correctly generates:

https://maps.googleapis.com/maps/api/staticmap?center=44.9545%2C-93.3365&zoom=10&size=640x640&scale=2&maptype=roadmap&style=feature%3Aall%7Cinvert_lightness%3Atrue%7Chue%3A0x57574e&key=xyz

staticmap

But when there are multiple style objects:

var params = {
    center: '44.9545,-93.3365',
    zoom: 10,
    size: '640x640',
    scale: 2,
    maptype: 'roadmap',
    style: [
        {
            feature: 'all',
            rules: {
                invert_lightness: true,
                hue: '0x57574e'
            }
        },
        {
            feature: 'road.highway',
            rules: {
                visibility: "simplified"
            }
        }
    ]
}

Generated URI is missing &style=: https://maps.googleapis.com/maps/api/staticmap?center=44.9545%2C-93.3365&zoom=10&size=640x640&scale=2&maptype=roadmap&style=feature%3Aall%7Cinvert_lightness%3Atrue%7Chue%3A0x57574e%7Cfeature%3Aroad.highway%7Cvisibility%3Asimplified&key=xyz

staticmap-1

Expected: https://maps.googleapis.com/maps/api/staticmap?center=44.9545%2C-93.3365&zoom=10&size=640x640&scale=2&maptype=roadmap&style=feature%3Aall%7Cinvert_lightness%3Atrue%7Chue%3A0x57574e%7C&style=feature%3Aroad.highway%7Cvisibility%3Asimplified&key=xyz

staticmap-2

The test is also missing &style=: https://github.com/moshen/node-googlemaps/blob/master/test/unit/utils/parseStylesTest.js#L48

semi-singleton architecture should be reviewed

Since the library doesn't export a constructor the _config object is global for all the calls you make within the same running process. This prevent the execution of multiple API calls that requires different configuration keys. For example running a simple geocoding as Business user will set google-client-id and google-private-key globally also for calls to the place API that don't need them.

Because of the way require works in node http://nodejs.org/api/modules.html#modules_caching
I cannot use 2 library in my code as a workaround.

Exporting a constructor would allow users to have multiple objects which don't share _config

Single Quotes in Addresses and Signing URLs

I run into some issues when using a business license key. When an address contains a single quote, such as Champagne au Mont d'Or, the geocoder will fail.

This is the error I get:

Unable to authenticate the request.
Provided "signature" is not valid for the provided "client".

Looks like the query params are not escaped correctly, because the URI contains ' instead of %27. If I change this manually, the request is valid.

Is this project on going?

Because the last update was a year ago and I would like to know if there is any chance that my pull request be accepted, and the npm module be updated with it.

TRAVIS

Simply adding a file .travis.yml file this project can be CI tested on each commit. Also a badge will be available to add to the README.md to encourage new user to use this lib

Passing tens of parameters to a method

Hi,

Wondered what your opinion on changing something like:

directions(origin, destination, callback, sensor, mode, waypoints, alternatives, avoid, units, language, departureTime, arrivalTime, region)

to an options object such as:

directions(origin, destination, callback, {
   mode: ...,
   waypoints: ...
   ...
})

would be? Finding myself counting parameters to get hold of the 'avoid' index and passing null,null,null,null,null is kinda ugly.

I might be up for doing a PR if there is enough interest.

Cheers,
Antony

Problem with buildUrl function and waypoints

The buildUrl function is not working well when the direction service is called with the waypoints parameter, the path after calling 'path = buildUrl(path, args)' is like this:

/maps/api/directions/json?origin=Vuelta%20de%20Haedo%20-%20Avenida%20Rivadavia%2C%20Haedo%2C%20Buenos%20Aires%2C%20Argentina&destination=Vuelta%20de%20Haedo%20-%20Avenida%20Rivadavia%2C%20Haedo%2C%20Buenos%20Aires%2C%20Argentina&waypoints=&waypoints=&language=es&sensor=false

Better Error Handling

Step to reproduce :

  1. Turn off the net
  2. try to run some simple function (I am trying directions api!)
  3. Why not to put actual error on console or throw it

SyntaxError: Unexpected token u

Any Good way to show/throw proper error which will direct the developer to find actual root cause?

is this library async ?

looking inside the library i note that's not make using async paradigm. Am i wrong about this ?

Request Denied

Hello Colin,

Thank you so much for making this library for gMaps/node!!
[EDIT: solved the original problem, new question though!]

Second question: I'm having some issues with Google Deniing some request:
{ error_message: 'This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console: Learn more: https://code.google.com/apis/console',
results: [],
status: 'REQUEST_DENIED' }

No big deal, I can selectively delete each key in the config var but will there be a reference in the log in the future that points specifically towards the one is been denied?

Thank you so much for your work,
Nicolò

Avoiding the query limit when using elevationFromPath

I'm trying to get the elevation data for some cycling routes, some of which have over a thousand different lat/lon coordinates. Unfortunately but understandably I keep getting a status of 'OVER_QUERY_LIMIT'. Does anyone know of a way to get around this?

How to return a displayed map?

I've been trying to use this wrapper for my node.js project, and I was wondering:
How would one use this API wrapper to return a non-static map?

I've used Google's API directly before, and have been able to manipulate and change maps through that, but I have not been able to find a way to get a non-static map using this node.js API wrapper (that also displays on the page).

My end goal is to perform a nearby places search and have an updating map that has a marker on the data returned by the API. Is there a way to do this using this maps API wrapper?

return result

Hi,

I don't understand how make result function, I m trying to do this 👍

var result;
gm.distance(from,to,function(err,data){
  result = data;
});
console.log(result);

Output : undefined

It is possible to return result directly

Successive request via gmAPI not working

Hi!
i have this function:

gmAPI.directions(params, function(err, res){
      var duration  = res.routes[0].legs[0].duration.text;
      console.log(duration);
});

inside a two for loop, and it doesn't pass the first call, it stays there. I tried settimeout with 1000 and 3000 but no go, any of you guys know the prob?

API License

Hi,
I started to use node-googlemaps to obtain directions from Google maps. I assumed that node-googlemaps uses the Google Maps Javascript API Version 3. Sadly I discovered that this assumption is incorrect, and the Google Maps API is being used.
This makes it unusable for my case, since the path field is missing in the routes, and much more important, its license does not allow the server-only use:

"The Directions API may only be used in conjunction with displaying results on a Google map; using Directions data without displaying a map for which directions data was requested is prohibited. Additionally, calculation of directions generates copyrights and warnings which must be displayed to the user in some fashion. For complete details on allowed usage, consult the Maps API Terms of Service License Restrictions."

I imagine that a big part of the people who use google maps on node.js do not displaying a map.
Am I overlooking something?

Meteor package

hello

I did a fork to make that support this good project on Meteor and publish on: atmosphere.meteor.com

someone has already done this?

Add Sign In Parameter option

As of v3.18 you can pass in a signed_in=true to use the newer map. I added it myself but think it would be a good addition.

Lat and lng of geocoder response

for a proper geocoded response, there is the geometry property, which has a location and that location has a lat and lng, but these are not parameters, they are getters, (they are functions).
i.e.:
the way google does it: googleResultObject.geometry.location.lat()
the way this module does it: googleResultObject.geometry.location.lat.

This can be confusing. I'd simply add this to the readme.

multi points itinerary

hi

is it possible to build something like this.... with google api?

1 / i enter a list of 25 or more addresses
2 / api calculate the best / fastest itinerary from ALL those points
3 / have a list as a result or export this as xls ?

thanks

this library THROWS

I just noticed there are 2 throw new Error('...') in methods that provide a callback.

Going to fix this as soon as I can

Issue installing this on our build server

Using codeship I'm having issues installing this dependency, the server throws this error while trying:

npm ERR! Failed resolving git HEAD (https://github.com/moshen/node-googlemaps.git) fatal: ambiguous argument 'new-major-version': unknown revision or path not in the working tree.

notes: http://codeship.com

'REQUEST_DENIED' when using places method

I created a server api key 'MY_KEY' with no server ip restriction for now.
My code is as follows,

if(req.query['lat'] != undefined && req.query['lng'] != undefined) {
    var GoogleMaps = require('googlemaps')
    var util = require('util')

    GoogleMaps.places(req.query['lat'] + ',' + req.query['lng'], 1, MY_KEY, function(err, response) {
      console.log('here is the response')
      console.log(response) //{ html_attributions: [], results: [], status: 'REQUEST_DENIED' }
    }) 

Is this correct? Is there any other configuration that needs to be added?

Channel ID

Does this library support channel ID?

Adding Key to all calls?

Traversing the Google Maps API documentation is not the easiest thing in the world but it looks as though they now recommend passing an API console key with all requests if you are not a business customer.

https://developers.google.com/maps/faq#keysystem

I see that the Places call has a key but it seems this should be refactored to a config parameter and passed with all calls if you aren't using a business account.

If folks agree with my interpretation of the meandering API docs I'll send a pull request.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.