vue google map api for user marker location

First, you need to include the Google Maps JavaScript API library in your Vue project. You can do this by adding the following script tag to your HTML file:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>

Replace YOUR_API_KEY with your actual Google Maps API key. Make sure to enable the Maps JavaScript API in the Google Cloud Platform Console and generate an API key.

Next, create a Vue component that will hold the map and handle the user marker location. Here's an example of a basic component structure:

<template>
  <div>
    <div id="map"></div>
  </div>
</template>

<script>
export default {
  mounted() {
    this.initMap();
  },
  methods: {
    initMap() {
      // Initialize the map
      const map = new google.maps.Map(document.getElementById("map"), {
        center: { lat: 0, lng: 0 },
        zoom: 8
      });

      // Add a marker on user's location
      navigator.geolocation.getCurrentPosition(
        position => {
          const userLocation = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
          };

          new google.maps.Marker({
            position: userLocation,
            map: map,
            title: "User Location"
          });

          // Center the map on user's location
          map.setCenter(userLocation);
        },
        error => {
          console.error(error);
        }
      );
    }
  }
};
</script>

<style>
#map {
  height: 400px;
  width: 100%;
}
</style>

In the mounted lifecycle hook, the initMap method is called to initialize the map. Inside the initMap method, a new instance of the map is created using the google.maps.Map constructor. The map is centered at latitude 0 and longitude 0 with a zoom level of 8.

The navigator.geolocation.getCurrentPosition function is used to get the user's current position. If the user grants permission to access their location, a marker is added to the map at their location using the google.maps.Marker constructor. The map is then centered on the user's location using the map.setCenter method.

If there is an error retrieving the user's location, an error message is logged to the console.

Finally, the component includes some basic CSS to set the height and width of the map container.

Remember to replace YOUR_API_KEY with your actual Google Maps API key.

That's it! You now have a Vue component that displays a Google Map and adds a marker at the user's location.