Как отфильтровать контакты на Google Map, извлеченные из конечной точки API JSON с помощью Vue - PullRequest
0 голосов
/ 26 сентября 2019

У меня есть карта с количеством выводов, выводы генерируются из конечной точки api (json).Я хочу отфильтровать контакты через вход, который имеет v-модал - критерии поиска уже установлены и извлекаются из того же API.

Даже если кто-то может дать несколько советов относительно того, где в VUEжизненный цикл фильтра должен произойти, то есть смонтированный, обновленный вычисленный ECT

Первоначально я использовал эту статью в качестве ссылки

https://medium.com/@limichelle21/integrating-google-maps-api-for-multiple-locations-a4329517977a

created() {
    axios
        .get(
            `https://cors-anywhere.herokuapp.com/myEndpoint`
        )
        .then(response => {
            // JSON responses are automatically parsed.
            this.allProperties = response.data;
            this.markers = this.allProperties.map(function (x) {
                return {
                    lat: parseFloat(x.lat).toFixed(3),
                    lng: parseFloat(x.lng).toFixed(3),
                    add: x.dispAddress,
                    propId: x.property_id,
                    propPrice: x.outputAskingPrice,
                    propImg: x.imagePath
                };
            });
            this.allProperties = response.data.map(x => {
                x.searchIndex = `${x.sellingStatus} ${x.priceType} ${x.typeNames[0]} ${x.typeNames[1]} ${x.dispAddress}`.toLowerCase();
                return x;
            });
        });
},

mounted: function () {
    var _this = this;

    function initMap() {
        var center = {
            lat: 53,
            lng: -3
        };
        var map = new google.maps.Map(document.getElementById("map-canvas"), {
            zoom: 10,
            center: center
        });
        var newPin = new google.maps.Marker({
            position: center,
            map: map
        });
    }
},

updated() {
    var _this = this;
    var map = new google.maps.Map(document.getElementById("map-canvas"), {
        zoom: 9,
        center: new window.google.maps.LatLng(55.961, -3)
    });
    var infowindow = new google.maps.InfoWindow({});
    var newPin;
    var count;
    for (count = 0; count < _this.markers.length; count++) {
        newPin = new google.maps.Marker({
            position: new google.maps.LatLng(
                _this.markers[count].lat,
                _this.markers[count].lng
            ),
            map: map,
            icon: "../assets/img/map-pin.png"
        });

        google.maps.event.addListener(
            newPin,
            "click",
            (function (newPin, count) {
                return function () {
                    infowindow.setContent(`<a href="/properties/property?propertyId=${_this.markers[count].propId}"> ${_this.markers[count].add} </a> <p> ${_this.markers[count].propPrice}</p><img src="${_this.markers[count].propImg}"><p>`);
                    infowindow.open(map, newPin);
                };
            })(newPin, count)
        );
    }

1 Ответ

0 голосов
/ 26 сентября 2019

Если у вас есть v-model в поле <input>, как указано в вашем вопросе, вы привязываете значение этого поля <input> к переменной, которая, вероятно, определена в части data вашего компонента Vue.Значение всегда актуально в модели (реактивное связывание).Вы можете посмотреть это значение, а затем вызвать функцию, которая обновляет Google Maps.Вот пример:

Vue.component('demo', {
  data () {
    return {
      inputField: ''
    };
  },
  created () {
    console.log('Component script loaded, HTML not yet ready, load the data from your backend. Use a flag like isLoading or similar to indicate when the data is ready to enable input.');
  },
  mounted () {
    console.log('Component mounted, HTML rendered, load Google Maps');
  },
  watch: {
    inputField (newValue) {
      console.log(`inputField changed to ${newValue}. Trigger here a method which update Google Maps. Make sure to debounce the input here, so that it does not trigger a Google Maps update too often.`);
    }
  },
  template: `
    <div>
      <input type="text" v-model="inputField" placeholder="Lookup place">
    </div>`
});

new Vue({ el: '#vue-demo-container' });
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="vue-demo-container">
  <demo></demo>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...