简体   繁体   中英

Nuxt js: Google maps markers wont show and loop is not working

I have a function that loops over an object to populate the markers. But when I do run the code, the loop is not working. Also when I do console.log , it is not showing me anything even in Vue DevTools. I am not using any Vue packages for the Google map. I just followed the documentation, and wrote the vanilla JavaScript functions.

Here is the whole function:

export default {
    layout:'adminLte',
    data(){
        return{
            address:{
                lat:7.0650673,
                lng:125.5961476
            },
            clinic:[],
            markersInfo:[],
        }
    },
    methods:{
        loadScript() {
            if (window.google && window.google.maps) {
                this.initMap();
                return;
            }
            var self = this;
            var script = document.createElement("script");
            script.onload = function() {
                if (!window.google && !window.google.maps)
                    return void(console.error("no google maps script included"));
                self.initMap();
            };
            script.async = true;
            script.defer = true;
            script.src = "https://maps.googleapis.com/maps/api/js?key=APIKEY&libraries=geometry";
            document.getElementsByTagName("head")[0].appendChild(script);
        },
        initMap(){

            var center = new google.maps.LatLng(this.address.lat, this.address.lng)
            const map = new google.maps.Map(document.getElementById('map'), {
                zoom: 13,
                center: center
            })
    
            //this are for the markers. even if i console log below. it wont show anything
            for (var i = 0; i < this.clinic.length; i++) {
                var clinicLat = this.clinic.data[i].lat;
                var clinicLng = this.clinic.data[i].lng;
                var details = this.clinic.data[i].name;
                var latLng = new google.maps.LatLng(clinicLat,clinicLng);
                console.log(details)
                var markers = new google.maps.Marker({
                    position: latLng,
                    map: map,
                    icon: {
                        url: "http://maps.google.com/mapfiles/ms/icons/yellow-dot.png"
                    },
                    size: new google.maps.Size(20, 20),
                });
                const contentString = '<div id="content"><p>' + details + '</p></div>';
                //for Info windows function
                console.log('Markers' + markers)
                this.infoWindowShow(markers, contentString);
                this.markersInfo.push(markers)
            }
      
        },
        infoWindowShow(markers, contentString) {
            var infowindow = new google.maps.InfoWindow({
                content: contentString
            });
            markers.addListener('click', function() {
                infowindow.open(markers.get('map'), markers);
            });
        },
        showMarker(id) {
            google.maps.event.trigger(this.markersInfo[id], 'click');
        },
        getClinicsList(){
              firebase.database().ref('clinics').on('value',(snapshot)=>{
                this.clinic = snapshot.val()
                console.log(snapshot.val())
                this.loadScript()
            })
        },
    },
    created(){
        console.log('created')
        this.getClinicsList()
 
        if (localStorage.getItem("user-email") === null) {
         this.$router.push('/login')
        }
    },
    mounted(){
        this.loadScript()
    }
}

The HTML element for map:

<div class="card-body table-responsive">
  <div id="map" style="width: 1200px; height: 600px;"></div>
</div>

Still the DevTools is empty, but the clinic array has values. 截屏

JSFiddle

Before the map markers even get created, the for -loop hits a runtime error, caused by a couple issues in your code.

Issue 1: clinic is not an Array

As seen in the screenshot, clinic is actually set to an Object :

诊所类型

The for -loop assumed clinic was an Array , and iterated with a numeric index, but that won't work properly with your Object . One solution is to use Object.values() for iteration like this:

// BEFORE:
// for (var i = 0; i < this.clinic.length; i++) {

for (const item of Object.values(this.clinic)) {

Issue 2: item.data does not exist

Your loop is trying to access a nonexistent data prop in each clinic item (ie, var clinicLat = this.clinic.data[i].lat ), but the lat and lng props are actually at the root of the object, as seen in the screenshot:

项目格式

So you could just access the props directly from the item reference. Using the corrected for -loop from above:

// BEFORE:
// for (var i = 0; i < this.clinic.length; i++) {
//   var clinicLat = this.clinic.data[i].lat;
//   var clinicLng = this.clinic.data[i].lng;
//   //...
// }

for (const item of Object.values(this.clinic)) {
  const clinicLat = item.lat
  const clinicLng = item.lng
  //...
}

Working JSFiddle with changes above

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM