简体   繁体   中英

Rendering multiple Google Maps API V3 markers from JSON

Attempting to plot multiple markers using Google Maps API V3 from JSON output by PHP from DB.

Map is initialized on page, however it does not populate with markers. Browser warns "Resource interpreted as Other but transferred with MIME type undefined."?

Suggestions for further troubleshooting / debugging please.

        <!--  load points from database into Locations JSON -->
    $(document).ready(function () {
        $.getJSON("map-service.php?action=listpoints", function(json) {

        if (json.Locations.length > 0) {
            for (i=0; i<json.Locations.length; i++) {
                var location = json.Locations[i];
                    addMarker(location); 
                    }
                }
            });

        function addMarker(location) {
            var point = new google.maps.LatLng(location.lat, location.lng); 
            var marker = new google.maps.Marker({
                position:point,
                map: map,
                title: location.name
                }); 
            };


    });

Validated sample JSON output from map-service.php?action=listpoints

{"Locations":[{"name":"Abco Mountain","lat":"49.424999","lng":"-125.855003"},{"name":"Adder Peak","lat":"49.248333","lng":"-125.320000"},{"name":"Alexandra Peak","lat":"49.738110","lng":"-125.489998"},{"name":"Argus Mountain","lat":"49.538612","lng":"-125.389999"},{"name":"Big Baldy Mountain","lat":"49.759998","lng":"-126.129997"}]}

My problem stemmed from how I had initialized the original map object. It wasn't visible in the code I shared ... apologies.

I did this:

var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

and should have done this:

this.map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 

I found the solution in this post Adding markers after map created Thanks @yitwail !

Try using jquery $.each for your looping.

if (json && json.Locations) {

$.each(json.Locations, function() { addMarker(this); });

});

Also, you'll probably want to call parseFloat on the lat and longiture inside your addMarker function.

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