Vue uses Google Map

1. Prerequisites for use

1. Google developer account

2. The account should be bound with a debit card for subsequent api charges (it seems that mainland debit cards are not supported)

2. Add new projects and add referenced API s

3. Create a credential in the credential and get the key of the api

Fourth, vue installation dependencies and initialization

npm install @googlemaps/js-api-loader
<template>
<!--To set the width and height of the box -->
 <div id="map" /> 
</template>


<script>
import { Loader } from "@googlemaps/js-api-loader"
const loader = new Loader({
  apiKey: "apikey", //api key
  version: "weekly", //Version
  libraries: ["places"],
})
export default {
 data() {
   return {
    google: '',
    map: '',
    service: '',
    infoWindow: '',
    marker: ''
   }
 },
 methods: {
  // map initialization
  initMap() {
      const mapOptions = {
        center: { lat: 22.602, lng: 114.043 },
        zoom: 6
      }
      loader
        .load()
        .then((google) => {
          this.google = google
          this.map = new google.maps.Map(
            document.getElementById("map"),
            mapOptions
          )
          // service location query class
          this.service = new google.maps.places.PlacesService(this.map)
          this.infoWindow = new google.maps.InfoWindow({ // map info window
            content: "",
            // disableAutoPan: true,
          })
          this.marker = new google.maps.Marker() // map marker class
          this.google.maps.event.addListener(this.map, 'click', this.clickMap) // Listen for map click events
        }).catch((e) => {
          console.log(e)
        })
    },
 }
}
</script>

5. Problems encountered

1. How to control the zoom value to automatically display the details of the map query location: For example, when I search for a map of Canada, it shows the size of the country, and when I search for a street map in Canada, it zooms in to show the specific buildings on the street. The control problem of the zoom level made me look for the api for a long time

this.marker.setMap(null) // Clear the previous mark

const request = {
      query:  'Ping An Building, Futian District, Shenzhen', // search text
      fields: ['name', 'geometry', 'place_id'], // Specify the data fields to be returned, can also be written as fields: ['all']
        }
this.service.textSearch(request, (results, status) => {
   if (status === this.google.maps.places.PlacesServiceStatus.OK) {
      console.log('search', results[0])
      let res = results[0]
      this.marker = new this.google.maps.Marker({ // Add map markers to search locations
          position: res.geometry.location,
          map: this.map,
      })
      this.map.setCenter(this.marker.getPosition()) // Centered on the search point
      let myLatLngBounds = new this.google.maps.LatLngBounds(res.geometry.viewport) // The geometry viewport of the current location
      this.map.fitBounds(myLatLngBounds) // Sets the viewport so that it contains the specified bounds. Change the zoom zoom level
      this.marker.addListener("click", (e) => { // Add click event to marker
          this.infoWindow.setContent(res.name);
          this.infoWindow.open(this.map, this.marker);
          this.map.setZoom(this.map.getZoom() + 1)
       })
       if(res.place_id) resolve(res.place_id)
   }
 })

https://developers.google.com/maps/documentation/javascript/reference/coordinates#LatLngBounds
google.maps.LatLngBounds class LatLngBounds Instances represent rectangles in geographic coordinates, including rectangles that intersect the 180-degree meridian.

 

 

2. How to get the value of country, city, district, county and street after searching for a location
Geocoding Service | Maps JavaScript API | Google Developers

  • country represents a country political entity and is usually the highest order type returned by the geocoder.
  • administrative_area_level_1 represents one level administrative entity below the country level. In the United States, such administrative levels refer to states. Not all countries have these administrative levels. In most cases, the admin_area_level_1 short name is very close to ISO 3166-2 subclasses and other widely disseminated lists; however, this implementation is not guaranteed as our geocoding results are based on various signals and location data.
  • administrative_area_level_2 represents a second-level administrative entity at the country level. In the United States, such administrative levels are referred to as counties. Not all countries have these administrative levels.
  • administrative_area_level_3 represents a third-level administrative entity under the country level. This type represents a smaller executive branch. Not all countries have these administrative levels
getDetailsInfo(placeId) {
      const request = {
        placeId,
        fields: ['all']
      }
      this.service.getDetails(request, (res, status) => {
        if (status === this.google.maps.places.PlacesServiceStatus.OK) {
          console.log('details', res)
          let addressList = res.address_components, street = res.formatted_address.split(' ')
          let i = 0;
          for(i; i < addressList.length; i++) {
            if (addressList[i].types.includes('country')) this.region.country = addressList[i].long_name
            if (addressList[i].types.includes('administrative_area_level_1')) this.region.province = addressList[i].long_name
            if (addressList[i].types.includes('locality')) this.region.city = addressList[i].long_name
            else if (addressList[i].types.includes('sublocality_level_1')) this.region.city = addressList[i].long_name
          }
        }
      })
    },

Tags: Javascript Front-end Vue.js

Posted by cdm2 on Sat, 22 Oct 2022 05:27:24 +0300