programing

Vue 컴포넌트의 맵을 동적으로 갱신할 필요가 있다

itsource 2023. 1. 27. 21:29
반응형

Vue 컴포넌트의 맵을 동적으로 갱신할 필요가 있다

다음 작업을 수행하는 구성 요소가 있습니다.

  • 글로벌 버스 메서드를 통해 형제 입력 구성 요소에서 문자열을 수신합니다.created()=> 동작
  • 스트링을 lat/lg 좌표로 조작합니다.geoDecoding()=> 동작
  • 약속 결과 좌표, 데이터 설정, 또한 다음을 통해geoDecoding()=> 동작
  • 리프레시showMap()이벤트 발생 후 변경된 데이터로 =>이(가) 작동하지 않습니다:(

디폴트 하드코드가 있는 소품(코멘트 아웃)이 있으니 참고하시기 바랍니다.showMap()그리고 효과가 있습니다.

  • 디버거를 설정했습니다.showMap()위도와 경도가 설정되어 있지 않은 것을 알 수 있습니다.이것들은 이상합니다.created()기동geoDecoding()

나는 가지고 싶다showMap()새로고침된 데이터()를 가져오는 모든 발생 이벤트를 새로고침합니다.this.latLong.latitude/this.latLong.longitude새로운 값에 따라 맵을 재검증합니다.이 시점에서 이 코드인스턴스를 여기에 붙여놓으면showMap()지도를 설치하지만 지도는 비어있다. 왜냐하면 그것은 lat/lang을 수신하지 않기 때문이다.geoDecoding().

코드:

<template>
    <div class="map-container" :id="theMap"></div>
</template>

<script>
    import { Bus } from "../main";

    export default {
        name: "GoogleMapsContainer",
        data() {
            return {
                theMap: "map-for-" + this.name,
                location: '',
                latLong: {
                    latitude: '',
                    longitude: ''
                },
            }
        },
        props: {
            name,
            // 'latitude': {
            //     type: Number,
            //     default: function () {
            //         return 39.50
            //     }
            // },
            // 'longitude': {
            //     type: Number,
            //     default: function () {
            //         return -98.35
            //     }
            // },
            // 'zoom': {
            //     type: Number,
            //     default: function () {
            //         return 4
            //     }
            // }
        },
        methods: {
            showMap() {
                debugger;
                this.map = new google.maps.Map(document.getElementById(this.theMap), {
                    center: {lat: this.latLong.latitude, lng: this.latLong.longitude},

                    zoom: this.zoom
                });
            },
            geoDecoding() {
                let geocoder = new google.maps.Geocoder();
                let theLocation = this.location;
                let latLong = this.latLong;

                    return new Promise(function (resolve, reject) {
                        geocoder.geocode({'address': (theLocation ? theLocation : 'canada')}, function (results, status) {
                            console.log(results);
                            if (status === google.maps.GeocoderStatus.OK) {
                                console.log(results[0].geometry.location.lat(), results[0].geometry.location.lng());
                                latLong.latitude = results[0].geometry.location.lat();
                                latLong.longitude = results[0].geometry.location.lng();
                            } else {
                                reject(status);
                            }
                        });
                    });
            }
        },
        mounted() {
            //this.geoDecoding();
            this.showMap();

        },
        created() {
            this.geoDecoding();
            Bus.$on('passLocation', (input) => {
                this.location = input;
                this.geoDecoding();
            });
        },


    }
</script>

<style scoped>
    .map-container {
        width: 80vw;
        margin: 5vh auto;
        height: 50vh;
        background: fuchsia;
    }
</style>

감시자를 사용해야 합니다.latLong:

  watch: {
    latLong: {
      handler: function(val, oldVal) {
        this.showMap();
      },
      deep: true
    }
  },

이를 실행하는 데 적합한 방법은 Google의 API 코드를 사용하는 것입니다.

panTo(<your-lat-lng-coords>);

이것을 코드에 짜넣기 위해서, 비동기 콜중에 설정합니다.

내가 약속할게methods:{geoDecoding(){}}다음과 같습니다.

geoDecoding() {
    let geocoder = new google.maps.Geocoder();
    let theLocation = this.location;
    let latLong = this.latLong;
    self = this;

    let service = new google.maps.places.PlacesService(this.map);
    var erez_markers = [];

    return new Promise(function (resolve, reject) {
        geocoder.geocode({'address': theLocation}, function (results, status) {
            if (status === google.maps.GeocoderStatus.OK) {
                console.log(results[0].geometry.location.lat(), results[0].geometry.location.lng());
                latLong.latitude = results[0].geometry.location.lat();
                latLong.longitude = results[0].geometry.location.lng();
                this.myLatlng = new google.maps.LatLng(latLong.latitude, latLong.longitude);
                self.map.panTo(this.myLatlng);//******* this would shift map on every instantiation with new lat/lng's
            } else {
                reject(status);
            }
        });
    });
}

상태 데이터는 기본값으로 설정되어 있기 때문에 다음과 같이 초기화 시 맵이 반환됩니다.

latLong: {
    latitude: 43.6532,
    longitude: -79.3832
},
location: '',
zoom: '',

맵 표시는 글로벌하게 설정되어 있기 때문에 임의의 장소에서 콜/인스턴스 할 수 있습니다.나는 그것을 아래 설치했다.methods:{showmap(){}}

this.map = new google.maps.Map(document.getElementById(this.theMap), {
                    center: {lat: this.latLong.latitude, lng: this.latLong.longitude},
                    zoom: this.zoom
});

언급URL : https://stackoverflow.com/questions/49995128/need-to-dynamically-refresh-map-in-vue-component

반응형