0

Thanks in advance for any help you can provide! I'm trying to create markers in my Google Map using JSON data. The good news is that I've got the data in the format I need it. The bad news is that I'm new to JSON, and I can't seem to get the markers to show up on the map. From the console's response, the issue seems to be the mapInit line at the bottom of the code below.

I have tried resolving this problem by reviewing solutions at different markers on google maps v3, Using JSON markers in Google Maps API with Javascript, and Google Maps API v3: Adding markers from an array doesn't work, among others. I've also tried duplicating the examples at http://weareallrobots.com/demos/map.html and other sites, but I'm still having trouble.

My code:

    <script>
        var directionsDisplay;
        var directionsService = new google.maps.DirectionsService();
        var map;

    function initialize() {
          var rendererOptions = {
          draggable: true,
          panel:document.getElementById('directions_panel')
         };

          directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
          var chicago = new google.maps.LatLng(41.850033, -87.6500523);
              var mapOptions = {
              zoom: 6,
              center: chicago,
              mapTypeId: google.maps.MapTypeId.ROADMAP
            }
          map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
          directionsDisplay.setMap(map);

  // HERE'S WHERE PROBLEMS START

          $.getJSON("mapall.js", {}, function(data){
          $.each(data.masterlocation, function(i, item){
            $("#markers").append('<li><a href="#" rel="' + i + '">' + item.nickname + '</a></li>');
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(item.latitude, item.longitude),
                map: map_canvas,
                title: item.nickname
            });
            arrMarkers[i] = marker;
            var infowindow = new google.maps.InfoWindow({
                content: "<h3>"+ item.nickname +"</h3>"
            });
            arrInfoWindows[i] = infowindow;
            google.maps.event.addListener(marker, 'click', function() {
                infowindow.open(map, marker);
            });
        });
    });
        }


    function calcRoute() {
    UNRELATED ROUTING CODE HERE  
        }

    // HERE'S WHERE MORE PROBLEMS START

$(function(){
    // initialize map (create markers, infowindows and list)
    mapInit();

    // "live" bind click event
    $("#markers a").live("click", function(){
        var i = $(this).attr("rel");
        // this next line closes all open infowindows before opening the selected one
        //for(x=0; x < arrInfoWindows.length; x++){ arrInfoWindows[x].close(); }
        arrInfoWindows[i].open(map, arrMarkers[i]);
    });
});


    </script>

My JSON Data

    [{"masterlocation":{"latitude":"33.5","nickname":"First","longitude":"-86.8"}},{"masterlocation":{"latitude":"34.7","nickname":"Second","longitude":"-86.6"}},

UPDATE 1

As per comments from geocodezip and Adam, I've updated my code to the below. I added the + symbol before latitude and longitude, and I replaced mapInit with initialize. However, I'm still not getting any markers to show up. Firebug is telling me that I have errors in my jQuery file, but I'm not sure if these are related. Thanks for sticking with me!

Code:

    // HERE'S WHERE PROBLEMS START

      $.getJSON("mapall.js", {}, function(data){
      $.each(data.masterlocation, function(i, item){
        $("#markers").append('<li><a href="#" rel="' + i + '">' + item.nickname + '</a></li>');
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(+item.latitude, +item.longitude),
            map: map_canvas,
            title: item.nickname
        });
        arrMarkers[i] = marker;
        var infowindow = new google.maps.InfoWindow({
            content: "<h3>"+ item.nickname +"</h3>"
        });
        arrInfoWindows[i] = infowindow;
        google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map, marker);
        });
    });
});
    }


function calcRoute() {
UNRELATED ROUTING CODE HERE  
    }

    // HERE'S WHERE MORE PROBLEMS START

    $(function(){
    // initialize map (create markers, infowindows and list)
    initialize();

    // "live" bind click event
    $("#markers a").live("click", function(){
    var i = $(this).attr("rel");
    // this next line closes all open infowindows before opening the selected one
    //for(x=0; x < arrInfoWindows.length; x++){ arrInfoWindows[x].close(); }
    arrInfoWindows[i].open(map, arrMarkers[i]);
    });
    });

JQuery errors

    TypeError: a is undefined
    [Break On This Error]   

    ...rn a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){...

    jquery.js (line 29)
    TypeError: a is undefined
    [Break On This Error]   

    ...rn a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){...

UPDATE 2

My current code is below, as well as the error codes I am getting in the console. New errors appeared when I reloaded the page, and they refer to the line in my javascript where function initialize first occurs. Maybe this is the problem?

Also, is it possible that the problem is in the JSON? Each JSON entry is preceded by the name of the MYSQL table, "Masterlocation" (see above.) In other JSON examples I've seen, the term that comes after the "." in "$.each(data.masterlocation)" only occurs once.

My Javascript:

    <script>
    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();
    var map;
    function initialize() {
    var rendererOptions = {
    draggable: true,
    panel:document.getElementById('directions_panel')
    };
    directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = {
zoom: 6,
center: chicago,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
directionsDisplay.setMap(map);
$.getJSON("mapall.js", {}, function(data){
console.log(data);
$.each(data.masterlocation, function(i, item){
console.log(item);
    $("#markers").append('<li><a href="#" rel="' + i + '">' + item.nickname + '</a></li>');
    var marker = new google.maps.Marker({
    position: new google.maps.LatLng(+item.latitude, +item.longitude),
    map: map,
    title: item.nickname
    });
    arrMarkers[i] = marker;
    var infowindow = new google.maps.InfoWindow({
        content: "<h3>"+ item.nickname +"</h3>"
    });
    arrInfoWindows[i] = infowindow;
    google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map, marker);
    });
    });
    });
    }

    function calcRoute() {
    ROUTING CODE

    var request = {
    origin: start,
    destination: end,
    waypoints: waypts,
    optimizeWaypoints: optimize,
    travelMode: google.maps.TravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
    directionsDisplay.setDirections(response);
    var route = response.routes[0];
    var summaryPanel = document.getElementById("directions_panel");                                              
}

$(function(){
// initialize map (create markers, infowindows and list)
initialize();

// "live" bind click event
$("#markers a").live("click", function(){
var i = $(this).attr("rel");
// this next line closes all open infowindows before opening the selected one
//for(x=0; x < arrInfoWindows.length; x++){ arrInfoWindows[x].close(); }
arrInfoWindows[i].open(map, arrMarkers[i]);
});
});

</script>

Javascript Errors from Console: these only occurred after I reloaded the page.

    Uncaught TypeError: Cannot read property 'length' of undefined jquery.js:29
    c.extend.each jquery.js:29
    (anonymous function) mapall:87
    b jquery.js:121
    w.onreadystatechange jquery.js:127

    Uncaught TypeError: Cannot read property 'length' of undefined jquery.js:29
    c.extend.each jquery.js:29
    (anonymous function) mapall:87
    b jquery.js:121
    w.onreadystatechange jquery.js:127
4

2 回答 2

0

Make sure the latitude and longitude are actually numbers in JS, not strings.

To do a type convert, just put a + in front of the string

position: new google.maps.LatLng(+item.latitude, +item.longitude)

For some reason, google's API was not built smart enough to handle passing in strings containing numbers....go figure.

EDIT

Ditto to the comment on your post as well - you are calling a function mapInit() but you should be calling the function initialize() from the looks of it.

EDIT2

This line:

map: map_canvas,

should be

map: map,
于 2013-07-07T19:42:44.483 回答
0

In addition to any other errors, the way you're accessing the JSON data doesn't match the format of that data.

Your code to access the JSON data is:

$.getJSON( "mapall.js", {}, function( data ) {
    $.each( data.masterlocation, function( i, item ) {
        ... use item.nickname, item.latitude, and item.longitude here
    });
});

Now there's nothing wrong with that code, if the JSON data looked like this:

{
    "masterlocation": [
        {
            "nickname": "First",
            "latitude": 33.5,
            "longitude": -86.8
        },
        {
            "nickname": "Second",
            "latitude": 34.7,
            "longitude": -86.6
        }
    ]
}

This JSON data is an object with a single property named masterlocation. That property is an array of objects, each one containing nickname, a string, and latitude and longitude, two numbers.

That's a pretty sensible way to lay out the JSON data. I would do it just about the same myself. (The only things I can think of changing would be the naming conventions: I'd probably use a name like locations instead of masterlocation because I like to see plural names for arrays, and I like shorter names for commonly-used properties, e.g. name, lat, and lng. But that's purely a matter of style—the structure I'd use is identical aside for names.)

Unfortunately, your actual JSON data looks like this:

[
    {
        "masterlocation": {
            "latitude": "33.5",
            "nickname": "First",
            "longitude": "-86.8"
        }
    },
    {
        "masterlocation": {
            "latitude": "34.7",
            "nickname": "Second",
            "longitude": "-86.6"
        }
    }
]

This is an array of two elements. Each element is an object with one property named masterlocation. Each masterlocation object contains the nickname, latitude, and longitude properties. And the latitude and longitude are strings instead of numbers like they should be.

It would be easy enough to change your code to work with this structure:

$.getJSON( "mapall.js", {}, function( data ) {
    $.each( data, function( i, item ) {
        var loc = item.masterlocation;
        ... use loc.nickname, +loc.latitude, and +loc.longitude here
    });
});

But if you have the option of changing the format of your JSON format, I'd do that instead. You had the right idea in your JavaScript code, just change the JSON output to match.

于 2013-07-08T19:16:27.613 回答