load-google-maps-api

:earth_asia: A lightweight Promise-returning helper for loading the Google Maps JavaScript API

Github星跟蹤圖

load-google-maps-api npm Version Build Status Bundle Size

A lightweight Promise-returning helper for loading the Google Maps JavaScript API

  • The Promise’s fulfilled callback is passed the google.maps object
  • Optionally set a timeout, an API key, the language, and more

Usage

Editable demo (CodePen)

const loadGoogleMapsApi = require('load-google-maps-api')

loadGoogleMapsApi().then(function (googleMaps) {
  new googleMaps.Map(document.querySelector('.map'), {
    center: {
      lat: 40.7484405,
      lng: -73.9944191
    },
    zoom: 12
  })
}).catch(function (error) {
  console.error(error)
})

N.B. Just like the Google Maps API itself, this module is client-side only.

Motivation

Without this module, you would need to specify a named global callback, and pass said callback’s name as a parameter in the script tag’s src. For example:

<script>
window.googleMapsOnLoad = function () {
  // `window.google.maps` available here
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=googleMapsOnLoad"></script>

This module abstracts this ceremony away, and fits better with modern bundlers like Browserify or Webpack.

API

const loadGoogleMapsApi = require('load-google-maps-api')

loadGoogleMapsApi([options])

Returns a Promise.

  • Fulfilled if loading was successful. The fulfilled callback is passed the google.maps object. If loadGoogleMapsApi is called multiple times on a page, the fulfilled callback will be passed the previously-loaded google.maps object.
  • Rejected if we weren’t able to load the Google Maps API after options.timeout.

See Usage.

options is an optional object literal:

Key, Description, Default
:--, :--, :--
apiUrl, The Google Maps API script tag URL, 'https://maps.googleapis.com/maps/api/js'
channel, Client usage reporting channel, undefined
client, Client ID, undefined
key, Your API key, undefined
language, Language, undefined
libraries, Supplemental libraries to load, []
region, Region, undefined
timeout, Time in milliseconds before rejecting the Promise, 10000
v, API version, undefined

Installation

$ yarn add load-google-maps-api

License

MIT

主要指標

概覽
名稱與所有者yuanqing/load-google-maps-api
主編程語言JavaScript
編程語言JavaScript (語言數: 1)
平台
許可證MIT License
所有者活动
創建於2016-01-01 05:00:25
推送於2021-03-17 14:09:59
最后一次提交
發布數16
最新版本名稱v2.0.2 (發布於 2020-03-07 16:50:30)
第一版名稱v0.0.1 (發布於 )
用户参与
星數173
關注者數2
派生數22
提交數82
已啟用問題?
問題數15
打開的問題數1
拉請求數3
打開的拉請求數2
關閉的拉請求數7
项目设置
已啟用Wiki?
已存檔?
是復刻?
已鎖定?
是鏡像?
是私有?