programing

Vue/Laravel에서 구글 맵 사용

procenter 2022. 8. 10. 21:35
반응형

Vue/Laravel에서 구글 맵 사용

구글 맵을 Vue 컴포넌트에 구현하려고 합니다.하지만 힘든 시간을 보내고 있다.사실 오류는 없습니다.하지만 지도도 없어요.- 네, 아래까지 제가 시도했던 건요.

라라벨 블레이드로 API를 설정합니다.

<script async defer src="https://maps.googleapis.com/maps/api/js?key={{env('GOOGLE_MAPS_API')}}&callback=initMap"></script>

다음으로 Vue 컴포넌트

data() {
        return {
            mapName: "map",
            //some other codes
        }           
},

mounted() {
        this.fetchEstates();
},
methods: {
        fetchEstates(page = 1) {
            axios.get('/ajax', {
                params: {
                    page
                }}).then((response) => {
                    // console.log(response);
                    this.estates = response.data.data;
                    //some other codes....
                    //some other codes....


},
computed: {

        //some other functions in computed... 
        //

        initMap: function(){
                    var options =
                        {
                            zoom : 6,
                            center : {
                                lat:34.652500,
                                lng:135.506302
                            }
                        };

                    var map = new google.maps.Map(document.getElementById(this.mapName), options);
                    var marker = new google.maps.Marker({
                        map: map,
                        icon: 'imgs/marker.png',
                        url: "/pages/estates.id",
                        label: {
                            text: this.estates.price,
                            color: "#fff",
                        },
                        position: {
                            lat: this.estates.lat,
                            lng: this.estates.lng
                        }
                    });
                        google.maps.event.addListener(marker, 'click', function () {
                            window.location.href = this.url;
                    });


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

그리고 지난 마커urlId 바인드 컨트롤러에 이것과 같다.

public function details($id)
{
    $estates = allestates::where('id', $id)->first();

    return view('pages.details', compact('estates'));

}

Vue js에서 뭔가 누락된 것이 있습니까?감사해요!

답글에서 우리의 논의부터, 나는 그 당신의 문제 때문에 사실을 알고 있다.this.estates때 아직도 정의되지 않은가.initMap()실행된다.당신이(axios을 통해) 채우는 비동기 연산을 사용하는 것이다.this.estates으므로, 그것은 런타임에 정의되지 않습니다.무엇을 해야 할까: 있다.

  1. 의 지도 initialisation 논리라.initMap()
  2. 후 axios 약속 해결될 때까지 모든 구글 지도 표지 만들기 이동한다.다른 메서드로, 즉 그 모든 추상 수 있다.insertMarkers()

또한 정의할야 한다는 것을 기억하다.estates그app/component 데이터에서, 그렇지 않으면 그것은 반응하지 않을 것이다.

다음은 예를 제시하겠습니다.

data() {
    return {
        mapName: "map",

        // Create the estate object first, otherwise it will not be reactive
        estates: {}
    }           
},

mounted() {
    this.fetchEstates();
    this.initMap();
},
methods: {
    fetchEstates: function(page = 1) {
        axios.get('/ajax', {
            params: {
                page
            }}).then((response) => {
                this.estates = response.data.data;

                // Once estates have been populated, we can insert markers
                this.insertMarkers();

                //pagination and stuff... 
            });
    },

    // Iniitialize map without creating markers
    initMap: function(){
        var mapOptions =
            {
                zoom : 6,
                center : {
                    lat:34.652500,
                    lng:135.506302
                }
            };

        var map = new google.maps.Map(document.getElementById(this.mapName), mapOptions);
    },

    // Helper method to insert markers
    insertMarkers: function() {
        var marker = new google.maps.Marker({
            map: map,
            icon: 'imgs/marker.png',
            url: "/pages/estates.id",
            label: {
                text: this.estates.price,
                color: "#fff",
            },
            position: {
                lat: this.estates.lat,
                lng: this.estates.lng
            }
        });

        google.maps.event.addListener(marker, 'click', function () {
            window.location.href = this.url;
        });
    }
},

업데이트: 또한 다음 데이터 구조의 문제에 대처하지 않은 것으로 나타났습니다.this.estates. 당신의 끝점 대신 개체에서, 그렇게 배열을 받고 있는 것으로 보인다.this.estates, 그리고 물론 배열을 반환할 것이다.this.estates.lat정의되지 않습니다.

어레이 전체를 반복하는 경우는,this.estates.forEach()마커를 추가하는 동안 각 개별 자산을 살펴봅니다.

data() {
    return {
        mapName: "map",

        // Create the estate object first, otherwise it will not be reactive
        estates: {}
    }           
},

mounted() {
    this.fetchEstates();
    this.initMap();
},
methods: {
    fetchEstates: function(page = 1) {
        axios.get('/ajax', {
            params: {
                page
            }}).then((response) => {
                this.estates = response.data.data;

                // Once estates have been populated, we can insert markers
                this.insertMarkers();

                //pagination and stuff... 
            });
    },

    // Iniitialize map without creating markers
    initMap: function(){
        var mapOptions =
            {
                zoom : 6,
                center : {
                    lat:34.652500,
                    lng:135.506302
                }
            };

        var map = new google.maps.Map(document.getElementById(this.mapName), mapOptions);
    },

    // Helper method to insert markers
    insertMarkers: function() {

        // Iterate through each individual estate
        // Each estate will create a new marker
        this.estates.forEach(estate => {
            var marker = new google.maps.Marker({
                map: map,
                icon: 'imgs/marker.png',
                url: "/pages/estates.id",
                label: {
                    text: estate.price,
                    color: "#fff",
                },
                position: {
                    lat: estate.lat,
                    lng: estate.lng
                }
            });

            google.maps.event.addListener(marker, 'click', function () {
                window.location.href = this.url;
            });
        });
    }
},

당신이 올린 스크린샷을 보면this.estates오브젝트 배열입니까?이 경우 어레이 전체를 반복할 필요가 있습니다.forEach

this.estates.forEach((estate, index) => { 
    console.log(estate.lat); 
    //handle each estate object here
});

또는 어레이의 첫 번째 항목을 다음과 같이 사용합니다.this.estates[0].lat첫 번째 항목에만 관심이 있는 경우.

언급URL : https://stackoverflow.com/questions/54479805/using-google-map-in-vue-laravel

반응형