简体   繁体   中英

How to make dynamic markers in google maps with jSON?

I am trying to create dynamic markers to load information from my json file. For some reason, the json data never loads. When I try to load one marker, it works fine without the json data. I don't see what the error is. In the console, it says "TypeError: (intermediate value).error is not a function". Here is the code below.

html script link

<script src="https://maps.googleapis.com/maps/api/js?CLIENT ID HERE 
  &v=3.21&callback=initMap"
    async defer></script>

External JS

var map;

function initMap() {
var myLatlng = {
    lat: -25.363,
    lng: 131.044
};
var centerZone = {
    lat: 0,
    lng: 0
};


map = new google.maps.Map(document.getElementById('map'), {
    center: centerZone,
    zoom: 3,
    minZoom: 3
});


$.getJSON('data/data.json', function(data) {
    $.each(data.markers, function(i, value) {

        var myLatlng = new google.maps.LatLng(value.lat, value.lon);
        alert(myLatlng);
        var marker = new google.maps.Marker({
            position: myLatlng,
            map: map,
            title: value.lon
        });

    });
}.error(function(words) {
    alert(words);
}));


var secretMessages = ['This', 'is', 'the', 'secret', 'message'];

/*marker.addListener('click', function() {
    map.setZoom(6);
    map.setCenter(marker.getPosition());
    attachSecretMessage(marker, secretMessages[0]);
  });*/

function attachSecretMessage(marker, secretMessage) {
    var infowindow = new google.maps.InfoWindow({
        content: secretMessage
    });

    marker.addListener('click', function() {
        infowindow.open(marker.get('map'), marker);
    });
}


// google.maps.event.addDomListener(window, 'load', initMap);
}

json data

{
"markers": [
    {
        "id": "1",
        "name": "Mesoamerica",
        "lat": "-25.363",
        "lon": "131.044",
        "zoomLevel": "6"
    }
]
}

The json data will have more objects inside, this is just a sample of how I want it.

You need to wait until the JSON data loads before doing anything with it. I suggest placing everything that relies on the JSON file in a $.done() function, like this:

$.getJSON('data/data.json').done(function(data){
    //everything else
});

Your browser will continue with the other lines of code while it's waiting for the $.getJSON function to return the data. That's why you're getting the "not a function" error; you're trying to call a function on something that doesn't exist and JS doesn't know what to do with it. If you place everything in $.done(), those lines won't execute until the JSON data has successfully been retrieved.

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