How to use the @google/maps.createClient function in @google/maps

To help you get started, we’ve selected a few @google/maps examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Bluegrass-Grief-Owls / coordin-eat / server / midpointAlgorithm / mockGetTravelTime.js View on Github external
const deg = 360/ num
		const fuzzRate = .2
		for (let p = 0; p < num; p++){
			const newCoord = [
				center[0] + chance.normal({mean: 1, dev: fuzzRate}) * radii[idx] * math.sin(math.unit(p*deg, 'deg')),
				center[1] + chance.normal({mean: 1, dev: fuzzRate}) * radii[idx] * math.cos(math.unit(p*deg, 'deg'))
			]
			result.push(newCoord)
		}
	})
	return result
}

// ==================== API REQUESTS & STUFF ===================

const client = require('@google/maps').createClient({
	key: process.env.GOOGLE_DIRECTIONS_KEY_1,
	Promise: Promise
})

const getTravelTime = (origin, dest, mode) => {
	const query = {
		origins: [origin],
		destinations: [dest],
		mode: mode
	}
	return client.distanceMatrix(query).asPromise()
		.then(res => {
			// console.log('response: ', res.json.rows[0].elements[0])
			return res.json.rows[0].elements[0].duration.value / 60.0
		})
		.catch(console.error.bind(console))
github slaylines / devsalaries / data / _utils / convert.js View on Github external
const DATA_FILE = '../entries.json';
const OUTPUT_FILE = 'entries.json';
const THROTTLING = 200; // milliseconds

require('dotenv').config();

const fs = require('fs');
const { msleep } = require('sleep');
const GoogleMapsApi = require('@google/maps');
const moment = require('moment');
const data = require(DATA_FILE);

const google = GoogleMapsApi.createClient({
  key: process.env.GOOGLE_API_KEY,
});

const write = (file) => {
  const json = JSON.stringify(data);
  fs.writeFile(file, json, 'utf8', err => console.log(err || ' ✔'));
};

const convertDate = (date) => {
  const [day, month, year, hour, minute, second] = date.match(/\d+/g);
  return moment([year, month, day, hour, minute, second]).unix();
};

const findCountryComponent = ({ types }) => {
  return types.includes('country');
};
github HelpAssistHer / help-assist-her / server / util / geocode-helpers.js View on Github external
'use strict'

const _ = require('lodash')
const config = require('config')
const googleMaps = require('@google/maps')
const R = require('ramda')
const P = require('bluebird')
const Log = require('log')

const log = new Log('info')

const googleMapsClient = googleMaps.createClient({
	key: config.googleMaps.key,
	Promise: P,
})

// the longitude and latitute of PregnancyCenter or FQHC are in pc.address.location, which is a GeoJSON point
// GeoJSON Point: { type: "Point", coordinates: [long, lat] }
//

// Google's geocoding API has the location part of the result in the format:
// "location" : {
//     "lat" : 37.4224764,
//     "lng" : -122.0842499
// }

// string => response data as promise
const getGoogleGeocode = fullAddress =>
github googlemaps / transport-tracker / backend / generate_paths.js View on Github external
* permissions and limitations under the License.
 */

/*eslint-disable no-shadow-global, unknown-require, no-undef-expression*/
const mapsApiKey = require('./tracker_configuration.json').mapsApiKey;
const {GTFS} = require('./gtfs');
const gtfs = new GTFS();
const _async = require('asyncawait/async');
const _await = require('asyncawait/await');
const Promise = require('bluebird');
const moment = require('moment');
const polyline = require('@mapbox/polyline');
const fs = require('fs');
const readline = require('readline');

const googleMapsClient = require('@google/maps').createClient({
  key: mapsApiKey,
  Promise
});

function generate_paths() {
  const trips = _await(gtfs.getTripsOrderedByTime());
  const tripsWithLocations = [];
  trips.forEach((trip, tripIndex) => {
    logProgress(`Processing trip ${tripIndex + 1} of ${trips.length}`);
    const timeCursor = moment(
      `${trip.departure_date} ${trip.departure_time}`,
      'YYYYMMDD HH:mm:ss'
    );
    const tripPoints = [];
    const stopInfo = _await(gtfs.getStopInfoForTrip(trip.trip_id));
    const stops = [];
github LMulvey / carbonfootprint-backend / src / lib / googleMapsApi.js View on Github external
export async function getDirections(
  origin,
  destination,
  mode = TRANSPORT_TYPES.DRIVING
) {
  const googleMapsClient = GoogleMaps.createClient({
    key: process.env.GOOGLE_MAPS_API_KEY
  });
  const asyncDirections = promisify(googleMapsClient.directions);
  try {
    const directions = await asyncDirections({
      origin,
      destination,
      mode: mode.toLowerCase()
    });
    return directions.json;
  } catch (e) {
    throw new Error(
      `Error occurred retrieving directions: ${JSON.stringify(e)}`
    );
  }
}
github googlemaps / google-maps-services-js / bin / run.js View on Github external
* 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 maps = require('@google/maps');
var args = maps.cli.parseArgs(process.argv.slice(3));
var options = {};

if (args.key != undefined) {
  options.key = args.key;
  delete args.key;
}

var client = maps.createClient(options);
var commands = Object.keys(client).join(', ');

try {
  var commandName = process.argv.length > 2 ? process.argv[2] : '';
  var commandFunc = client[commandName];
  if (commandFunc == undefined) {
    throw {message: `'${commandName}' is not a valid command, usage is:

googlemaps command --arg1 'value1' --arg2 'value2'

where command is one of: ${commands}

For arg details, see: https://googlemaps.github.io/google-maps-services-js/docs/GoogleMapsClient.html
`};
  }
  commandFunc(args, maps.cli.callback)
github lv275python / eventually.api / eventually / static / src / containers / event / EventLink.js View on Github external
fetchAddress() {
        const googleMapsClient = require('@google/maps').createClient({
            key: googleMapsAPIKey
        });
        let location = [this.props.latitude, this.props.longitude];

        googleMapsClient.reverseGeocode({'latlng': location}, (err, response) => {
            if (response.status == 200) {
                let addressComponents = response.json.results[0].address_components;
                let city = this.fetchAddressComponent(addressComponents, 'locality');
                let cityName = city ? city.short_name : null;
                let country = this.fetchAddressComponent(addressComponents, 'country');
                let countryName = country ? country.long_name : null;

                let formattedAddress = [countryName, cityName].filter(el => el).join(', ');
                return this.setState({address: formattedAddress});
            }
        });
github NGRP / node-red-contrib-viseo / node-red-contrib-google-maps / google-places.js View on Github external
let parameters = {},
        keys = Object.keys(param);

    for (let i=0; i
github lv275python / eventually.api / eventually / static / src / containers / event / EventEdit.js View on Github external
fetchAddress() {
        const googleMapsClient = require('@google/maps').createClient({
            key: googleMapsAPIKey
        });
        let location = [this.props.latitude, this.props.longitude];
        googleMapsClient.reverseGeocode({'latlng': location}, (err, response) => {
            if (response.status == 200) {
                let addressComponents = response.json.results[0].address_components;
                let city = this.fetchAddressComponent(addressComponents, 'locality');
                let cityName = city ? city.short_name : null;
                let street = this.fetchAddressComponent(addressComponents, 'route');
                let streetName = street ? street.long_name : null;
                let number = this.fetchAddressComponent(addressComponents, 'street_number');
                let numberStreet = number ? number.long_name : null;
                let formattedAddress = [streetName, cityName,numberStreet].filter(el => el).join(', ');
                return this.setState({formattedAddress: formattedAddress});
            }
        });

@google/maps

Node.js client library for Google Maps API Web Services

Apache-2.0
Latest version published 5 years ago

Package Health Score

61 / 100
Full package analysis

Popular @google/maps functions