#What is the proper way of using a google map on Astro? I dont use any UI Framework

3 messages · Page 1 of 1 (latest)

coarse lake
#

What is the proper way of using a google map on Astro? I dont use any UI Framework

noble ploverBOT
#

Hi @coarse lake. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To use a Google Map in Astro without a UI framework, you have a couple of options:

  1. You can use the astro-geo-map integration, which allows you to embed an interactive map in your webpage using Leaflet.js. This integration is available in the Astro Integrations Directory (https://astro.build/integrations/19/). However, note that this uses Leaflet.js, not Google Maps specifically.

  2. Alternatively, you can use a client-side script to load and initialize a Google Map. Here's how you can do this:

  3. First, create an Astro component for your map:

---
// MyMap.astro
---

<div id="map" style="height: 400px; width: 100%;"></div>

<script>
  function initMap() {
    const map = new google.maps.Map(document.getElementById("map"), {
      center: { lat: -34.397, lng: 150.644 },
      zoom: 8,
    });
  }

  window.initMap = initMap;
</script>

<script async defer src="<https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>>
  1. Then, use this component in your Astro page:
---
import MyMap from '../components/MyMap.astro';
---

<html>
  <body>
    <h1>My Google Map</h1>
    <MyMap />
  </body>
</html>

This approach uses Astro's client-side scripts (https://docs.astro.build/en/guides/client-side-scripts/#_top) feature to load and initialize the Google Maps JavaScript API. Remember to replace YOUR_API_KEY with your actual Google Maps API key.

Note that this method will load the Google Maps script on the client side, which aligns with Astro's philosophy of minimizing JavaScript usage (https://docs.astro.build/en/concepts/why-astro/#easy-to-use) by default while still allowing you to add interactivity when needed.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: