Git Product home page Git Product logo

load-google-maps-api's Introduction

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

load-google-maps-api's People

Contributors

fhemberger avatar jncorpron avatar rainboxx avatar yuanqing 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

load-google-maps-api's Issues

The "key" option specified but not working.

I load your API as follow...

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

loadGoogleMapsApi().then(function (googleMaps) {
new googleMaps.Map(document.querySelector('#Map'), {
    center: {
    lat: 40.7484405,
    lng: -73.9944191
    },
    key: 'AIza################pmSvQ', // my api key
    zoom: 19
})
}).catch(function (error) {
    console.error(error)
})

The map showed up with the warning message in the console.

Google Maps JavaScript API warning: NoApiKeys

Also, your codepen for this api is not working properly.

Access extra libraries

I want to use the Google API PlacesService, therefore I passed libraries: ['places'] to load-google-maps-api constructor. How can I now access it? The parameter passed to callback when Google Maps is loaded doesn't seem to contain a reference to e.g. PlacesService.

Multiple Calls

Thanks for sharing the code!

However, there are issues when the function is called multiple times before the api has loaded. This may happen if there are multiple components that require the api. I have run into this using Vue but seems like it could happen with any component-based framework.

First, for multiple calls, multiple promises are being generated, but only get resolved during the callback function, which gets deleted after the first resolve. I would suggest saving the initial promise, and returning it on subsequent calls.

Second, there is no check to see if the script already exists, so it will get appended a second time while waiting for the first to resolve. A simple document.getElementById could check for this.

Key working in dev but not production

In production, the generated script tag is lacking key=###:
image but it is working in development. Have you seen this before? It's running on Heroku:

async mounted() {
    const googleMapApi = await loadGoogleMapsApi({
      key: process.env.API_KEY
    })
    this.google = googleMapApi
    this.initializeMap()
  },
  methods: {
    initializeMap() {
      const mapContainer = this.$refs.googleMap
      this.map = new this.google.Map(mapContainer, this.mapConfig)
    }

I am running it through nuxt with SSR off. It will add libraries to the generated script src but not keys, if I add keys directly or through ApiUrl it does not add a key parameter :(
It runs locally and on heroku local web perfectly...

SetCenter

How can i SetCenter in this Component? thanks for your reply

Feat proposal | Extend to add google maps extended libraries

There are some libraries, that help the users to do some complex operations easier. They are listed here:
http://googlemaps.github.io/libraries

When the user needs to use any of these libraries, they would still need to do it in the manual way. However this library has the potential to give also that flexibility to the user, so they can decide which library to add to the project.

What do you think? Would it be a scope for this package? If so, I'd be glad to make a PR

"Missing key error" when app deployed

The map loads without error when I'm working on localhost but when I deploy it loads briefly and then turn into an error (see attached gif).
Google Maps JavaScript API error: MissingKeyMapError https://developers.google.com/maps/documentation/javascript/error-messages#missing-key-map-error
loadmapkeyerror

I created a new key and that didn't change the behavior on the deployed code. Any suggestions?
Update - it appears that for localhost you don't need to the keys to see the map. There is an error about missing keys on localhost but it doesn't cause the map to disappear.

MarkerCluster feature

Is there a way to use MarkerCluster with this?

Google Docs for Marker Clustering

It also needs us to import via <script> tag. How would I go about modifying this so that we can implement this functionality?

I was thinking of doing it in a similar way you did here but in another package. Do you think we should try to integrate MarkerCluster into this library?

promises in IE

the error
SCRIPT5009: 'Promise' is undefined

the cause
return new Promise(function (resolve, reject) {

fail safe for re-execution of the promise if the option changes.

Hi,

This may be a niche scenario, but is it possible to make a way to reset the promise when the options are changed? I want to know if this is a good idea before trying to solve it.

My exact scenario is changing the language. So checking the code option is

  • if I delete the promise and then tag a id for the script tag. so that when an options change I reload it with another script.

Constantly seeing 'Could not load the Google Maps API'

Hello,

We are tracking the errors in our application and we do use load-google-maps-api module. There approx 30 events with 'Could not load the Google Maps API' message. Do you have any idea why this may happen. We do see such failures from different devices and resolutions.

How to use markers?

Hi, thanks for module.
I wrote a code, and it work without webpack.

function initialize() {
	let location = [
		['1', 44.4991128, 11.2966662, 1, 'Bologna'],
		['2', 45.4627124, 9.1076931, 1, 'Milano'],
		['3', 44.4469563, 8.8207929, 1, 'Genova'],
	];
	let map = new google.maps.Map(document.getElementById('map'), {
		zoom: 8,
		center: new google.maps.LatLng(44.8585384, 10.3738929),
		mapTypeId: google.maps.MapTypeId.ROADMAP
	});
	let infowindow = new google.maps.InfoWindow();
	for (let i = 0; i < location.length; i++) {
		let marker = new google.maps.Marker({
			position: new google.maps.LatLng(location[i][1], location[i][2]),
			map: map,
			title: location[i][0]
		});
		google.maps.event.addListener(marker, 'click', (function (marker, i) {
			return function () {
				let mapTemplate = `
                                <h4>Filiale del Trentino Alto Adige </h4>
                                <p>Asta Centrale Blocco 3/A Galleria B n. 90 Centergross  40050 Funo di Argelato (BO) </p>
                                <ul>
                                    <li>
                                        <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path d="M16.2532 11.5765C15.3796 10.7118 14.0035 10.6122 13.0167 11.3456L12.46 11.7757C12.1522 12.0065 11.7267 11.9748 11.4551 11.7032L6.57556 6.81868C6.30397 6.54706 6.27229 6.12153 6.50314 5.8137L6.93315 5.23878C7.66644 4.25191 7.56686 2.88026 6.7023 2.00656L5.34436 0.648482C4.46622 -0.216161 3.05396 -0.216161 2.17583 0.648482L1.23885 1.58103C-0.159836 2.96627 -0.404266 5.14372 0.659456 6.8051C3.35271 11.0468 6.94673 14.6457 11.1835 17.3438C12.8447 18.4031 15.0174 18.1586 16.4071 16.7643C17.0725 16.0943 18.0683 15.3067 17.9959 14.2474C18.0773 13.1383 16.9367 12.2872 16.2532 11.5765Z" fill="#FA6100"/>
                                        </svg>
                                        <a href="tel:0422 362826">0422 362826</a>
                                    </li>
                                    <li>
                                        <svg width="18" height="15" viewBox="0 0 18 15" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path d="M14.885 3.85428H14.3893V0H3.08342V3.85428H2.58776C1.16091 3.85428 0 5.01493 0 6.44204V11.5446C0 12.9714 1.16091 14.1324 2.58776 14.1324H14.8847C16.3118 14.1324 17.4727 12.9714 17.4727 11.5446V6.44204C17.4727 5.01493 16.3118 3.85428 14.885 3.85428ZM4.36818 1.28476H13.1045V6.16684H4.36818V1.28476Z" fill="#FA6100"/>
                                            <path d="M3.08379 11.6913C3.43856 11.6913 3.72617 11.4037 3.72617 11.0489C3.72617 10.6942 3.43856 10.4066 3.08379 10.4066C2.72901 10.4066 2.44141 10.6942 2.44141 11.0489C2.44141 11.4037 2.72901 11.6913 3.08379 11.6913Z" fill="white"/>
                                        </svg>
                                        <a href="tel:0422363139">0422 363139</a>
                                    </li>
                                    <li>
                                        <svg width="18" height="13" viewBox="0 0 18 13" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path d="M0 11.1048V1.89523C0.0140598 1.85799 0.0246046 1.82074 0.0351494 1.7835C0.221441 0.764357 1.14236 0.00253939 2.21793 0.00253939C6.73814 -0.000846464 11.2583 -0.000846464 15.7786 0.00253939C16.8014 0.00253939 17.6907 0.69664 17.9332 1.65484C17.9543 1.7361 17.9789 1.81736 18 1.89523V11.1048C17.9859 11.1285 17.9754 11.1556 17.9684 11.1793C17.7997 12.0799 17.1529 12.7706 16.2285 12.9365C15.7961 13.0144 15.3427 12.9941 14.8998 12.9975C10.6924 13.0008 6.48155 13.0008 2.27065 12.9975C1.23726 12.9975 0.365554 12.3677 0.0843585 11.4264C0.0527241 11.3248 0.0281195 11.2131 0 11.1048ZM6.12302 6.34425C5.84183 6.61173 5.57469 6.86567 5.31459 7.11961L2.44991 9.86893C2.27768 10.0348 2.19684 10.2211 2.27065 10.4513C2.4007 10.8644 2.90334 10.9659 3.24077 10.6409C4.43234 9.49987 5.62039 8.35545 6.80492 7.20764C6.8471 7.15686 6.88928 7.10607 6.92443 7.04851C7.02285 7.13654 7.08612 7.19072 7.1529 7.24489L8.58348 8.49766C8.85413 8.73467 9.13884 8.73128 9.41301 8.49427C9.90861 8.06427 10.4042 7.63088 10.8963 7.19749C10.942 7.15686 10.9912 7.11623 11.0475 7.06883C11.4938 7.50221 11.9332 7.92545 12.3691 8.34868L14.7522 10.6443C14.9139 10.8 15.1002 10.8745 15.3251 10.817C15.761 10.7019 15.8875 10.2143 15.5571 9.89263C14.7592 9.12066 13.9613 8.34868 13.1599 7.58348C12.7346 7.17379 12.3058 6.7641 11.8735 6.34764C11.9297 6.29685 11.9754 6.25283 12.0246 6.2122L13.7645 4.68857L15.5466 3.12769C15.7188 2.97871 15.7856 2.79249 15.7294 2.57918C15.6837 2.38618 15.529 2.23382 15.3286 2.1898C15.1037 2.13224 14.9209 2.21012 14.7522 2.3591C12.8823 3.99785 11.0123 5.63999 9.13533 7.27536C9.08963 7.31599 9.04042 7.35324 8.99121 7.39725L6.31634 5.04408C5.28647 4.14344 4.25308 3.24281 3.21968 2.33878C3.058 2.19658 2.87522 2.12886 2.65729 2.18642C2.45694 2.23382 2.3058 2.3828 2.26011 2.57579C2.20738 2.79249 2.27768 2.97532 2.44991 3.1243C3.18805 3.76761 3.92619 4.41431 4.66081 5.05763L6.12302 6.34425Z" fill="#FA6100"/>
                                        </svg>
                                        <a href="mailto:[email protected]">[email protected]</a>
                                    </li>
                                </ul>
                                <a href="" class="btn">Scopri la filiale</a>
                                <a href="" class="btn">Imposta il navigatore</a>
                            `;
				console.log(provinceData);
				const province = location[i][4];
				fetch('http://rewind.altuofianco.com/wp-json/wp/v2/posts?search=' + province)
					.then(response => response.json())
					.then(json => console.log(json));
				infowindow.setContent(location[i][0]);
				infowindow.open(map, marker);
			}
		})(marker, i));
	}
}

initialize();

And now i want to move them to webpack.
But i don't know how to do that.

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.