[Vuejs]-How can I display selected city of combo box in the google map on the vue component?

2👍

This should be enough to help you move forward in the right direction.

https://jsfiddle.net/jacobgoh101/pojy5htn/12/

e.g.

new Vue({
  el: '#app',
  template: `
        <div>
            <select v-model="selectedCity">
                <option v-for="city in cities" :value="city.id">{{city.name}}</option>
            </select>
            <h4>Selected city key: {{selectedCity}}</div>
        </div>
    `,
  data: {
    cities: [{
        id: 1,
        name: "Manchester",
        lat: 53.480759,
        lng: -2.242631
      },
      {
        id: 2,
        name: "London",
        lat: 51.507351,
        lng: -0.127758
      }
    ],
    selectedCity: ""
  },
  mounted() {
    var mapProp = {
      center: new google.maps.LatLng(0, 0),
      zoom: 5,
    };
    this.map = new google.maps.Map(document.getElementById("map"), mapProp);
  },
  created() {
    this.map = null;
    this.mark = null;
  },
  watch: {
    selectedCity(v) {
      // get the selecte city
      const city = this.cities.filter(obj => obj.id === v).pop();

      //this remove the previous marker on the map
      if (this.mark) this.mark.setMap(null);

      // set map center to the location
      this.map.setCenter({
        lat: city.lat,
        lng: city.lng
      });

      // create a marker for the city and assign it to `this.map`
      this.mark = new google.maps.Marker({
        position: {
          lat: city.lat,
          lng: city.lng
        },
        map: this.map,
        draggable:true,
      });
    }
  }
});

Leave a comment