简体   繁体   中英

Google Maps v3 - Markers not displaying

I am trying to place multiple markers on a Google Map (API v3). I looked at the Google docs and also this thread . The map draws and centers to the init point but no markers are showing on the map.

Firebug is not reporting any errors.

Here is the JS

<script type="text/javascript">

   var map;

    function initialize() {
            var mapOptions = {
            zoom: 8,
            center: new google.maps.LatLng(41.056466,-85.3312009),
            mapTypeId: google.maps.MapTypeId.ROADMAP
            };

    map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);

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

    //Add 1st marker
    var Latlng_0 = new google.maps.LatLng(41.057814980291,-85.329851919709);
    var marker_0 = new google.maps.Marker({
        position: Latlng_0,
                  title:"0"});

        marker_0.setMap(map);

    //Add 2nd marker
    var Latlng_1 = new google.maps.LatLng(41.065294480291,-85.330151019708);
    var marker_1 = new google.maps.Marker({
        position: Latlng_1,
        title:"1"});
        marker_1.setMap(map);

    google.maps.event.addDomListener(window, 'load', initialize);
</script>

Thanks for looking!

The reason the markers are not showing up is because that part of the code is getting executed before the load event gets fired and the initialize method gets invoked - at that point your map variable is already created but is still null.

try adding the code to add the markers inside the initialize method

var map;

function initialize() {
    var mapOptions = {
        zoom: 8,
        center: new google.maps.LatLng(41.056466,-85.3312009),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);

    // Add 1st marker
    var Latlng_0 = new google.maps.LatLng(41.057814980291,-85.329851919709);
    var marker_0 = new google.maps.Marker(
        {
            position: Latlng_0, 
            title:"0"
        }
    );

    marker_0.setMap(map);

    //Add 2nd marker
    var Latlng_1 = new google.maps.LatLng(41.065294480291,-85.330151019708);
    var marker_1 = new google.maps.Marker(
        {
            position: Latlng_1,
            title:"1"
        }
    );

    marker_1.setMap(map);
}

google.maps.event.addDomListener(window, 'load', initialize);

see this jsfiddle here where the markers are showing up http://jsfiddle.net/KvugB/

I use this code. I hope it helps you:

(function() {

window.onload = function() {

    // Creating a new map
    var map = new google.maps.Map(document.getElementById("map"), {
      center: new google.maps.LatLng(41.056466, -85.3312009),
      disableDefaultUI: false,
      zoom: 16,
      mapTypeId: google.maps.MapTypeId.SATELLITE
    });


    // Creating the JSON data
    var json = [
        {
            "title": "Title 1",
            "lat": 41.057814980291,
            "lng": -85.329851919709,
            "description": ""
        },
        {
            "title": "Title 2",
            "lat": 41.057814981000,
            "lng": -85.8048,
            "description": ""
        },
    ]

    var styles = [
  {
   "featureType": "water",
   "elementType": "geometry.fill",
   "stylers": [
      { "visibility": "on" },
      { "color": "#0077bb" },
  { "lightness": 70 }
      ]
      },{
      "featureType": "landscape.natural",
      "elementType": "geometry.fill",
      "stylers": [
      { "visibility": "on" },
      { "saturation": -100 },
      { "color": "#699e6b" },
      { "lightness": 76 }
      ]
      },{
      "featureType": "poi.park",
      "elementType": "geometry.fill",
      "stylers": [
      { "visibility": "off" }
      ]
      },{
      "featureType": "road.local",
      "elementType": "geometry.fill",
      "stylers": [
      { "visibility": "on" },
      { "color": "#ffffff" }
      ]
      }
      ];

       map.setOptions({styles: styles});



    // Creating a global infoWindow object that will be reused by all markers
    var infoWindow = new google.maps.InfoWindow();

    // Looping through the JSON data
    for (var i = 0, length = json.length; i < length; i++) {
        var data = json[i],
            latLng = new google.maps.LatLng(data.lat, data.lng);




        // Creating a marker and putting it on the map
        var marker = new google.maps.Marker({
            position: latLng,
            map: map,
            title: data.title
        });

        // Creating a closure to retain the correct data, notice how I pass the current data in the loop into the closure (marker, data)
        (function(marker, data) {

            // Attaching a click event to the current marker
            google.maps.event.addListener(marker, "click", function(e) {
                infoWindow.setContent(data.description);
                infoWindow.open(map, marker);
            });


        })(marker, data);

    }

}

   })();

This is a reply to @JoanManuelHernández's answer, but I can't post formatted code in a comment.

Joan, your solution is excellent; it's very similar to how I would do it myself. Creating an array of marker locations is way better than using individual variables for each one.

I'd like to suggest a couple of minor improvements. One is where you have the array named json . That isn't a very descriptive name; json could mean any kind of data. How about calling it something like places or locations or the like?

Next, where you have the loop that creates the closure to handle the asynchronous callback, I think it's a bit easier to understand how it works if you move the entire loop body into its own function. Then you don't need the inline anonymous function. So this code:

// Looping through the JSON data
for (var i = 0, length = json.length; i < length; i++) {
    var data = json[i],
        latLng = new google.maps.LatLng(data.lat, data.lng);

    // Creating a marker and putting it on the map
    var marker = new google.maps.Marker({
        position: latLng,
        map: map,
        title: data.title
    });

    // Creating a closure to retain the correct data, notice how I pass the current data in the loop into the closure (marker, data)
    (function(marker, data) {

        // Attaching a click event to the current marker
        google.maps.event.addListener(marker, "click", function(e) {
            infoWindow.setContent(data.description);
            infoWindow.open(map, marker);
        });


    })(marker, data);
}

would become:

// Looping through the places list
for( var i = 0, length = places.length;  i < length;  i++ ) {
    addPlace( places[i] );
}

// Add one place marker
function addPlace( place ) {
    var latLng = new google.maps.LatLng( place.lat, place.lng );

    // Creating a marker and putting it on the map
    var marker = new google.maps.Marker({
        position: latLng,
        map: map,
        title: place.title
    });

    // Attaching a click event to the current marker
    google.maps.event.addListener( marker, "click", function(e) {
        infoWindow.setContent( place.description );
        infoWindow.open( map, marker );
    });
}

It does the same thing, just a little simpler this way.

One other thought: The styled map stuff is very cool—I'm a big fan of styled maps myself—but I wonder if it should be left out here for the sake of simplicity, since it isn't related to the OP's question?

Feel free to incorporate any of these ideas into your own answer if you like them, and if anyone else finds this variation useful, please upvote Joan's answer since that's where the original code came from.

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