无法让 Google 地图 api v3 显示来自 xml 文件的标记

Can't get Google Maps api v3 to display markers from xml file

我应该掌握什么是正常工作的 JS 和 xml 文件...我只是想利用已免费提供给所有人的庞大位置数据库使用 - 位于@ http://www.craftbeer.com/breweries/brewery-locator/find-a-us-brewery

我尝试使用他们的 maps.js 和 xml 文件...但我最终得到的只是一个空白的地图屏幕...

这是 Javascript...

/*********************************************

**Google Maps Custom API work**

This code can be reused on any site to display a local map of breweries from our local iMis dump, as well as pull in beermapping.

Hey! Don't forget to include API in functions.php! Function is conditionally initialized in footer.php

*/  

//Set up variables to create marker
var gmarkers = [];
var mapMarkers = [];
var geocoder = new google.maps.Geocoder(); 
var icon = 'http://www.craftbeer.com/wp-content/uploads/marker.png';

//Initialize Map
function view_map(xml_file, latitude, longitude, varZoom) { 
        console.log('view map');
        map = new google.maps.Map(document.getElementById("map_canvas"), { //Create the map, Set Default Zoom level and type

        center: new google.maps.LatLng(latitude, longitude),
            zoom: varZoom,
            mapTypeId: 'roadmap',
            panControl: true,
            zoomControl: true,
            mapTypeControl: false,
            scaleControl: true,
            streetViewControl: false,
            overviewMapControl: false
        });


//-- Listeners --//
google.maps.event.addListener(map, 'center_changed', function() {
   console.log('center changed');
   //clearMarkers();    
  });

google.maps.event.addListenerOnce(map, 'tilesloaded', function(){
    //this part runs when the mapobject is created and rendered
    console.log("loaded");
    $("#loading-screen").fadeOut(250, function(){});
    $("#loading-icon").fadeOut();
    //google.maps.event.addListenerOnce(map, 'tilesloaded', function(){   });
}); 


//console.log(xml_file);
var download_file = xml_file; //this variable is passed in so we can re-use this script

//Pull in the XML feed
downloadUrl(download_file, function(data) { 
    console.log("downloading xml");
    var xml = data.responseXML;
    var markers = xml.documentElement.getElementsByTagName("marker");


    //Loop through all markers in the XML file
    for (var i = 0; i < markers.length; i++) {
        var state = markers[i].getAttribute("state");
        var x   = markers[i].getAttribute("lat");
        var y   = markers[i].getAttribute("lng");

        if ( state != 'PR' && state != 'VI' &&  state != 'GU' && x != "" ){
        //console.log(state);

        var ids = parseFloat(markers[i].getAttribute("id"));

        var z = new google.maps.LatLng(x,y,i);
        //console.log(x);

        var _id = markers[i].getAttribute("id");
        var name = markers[i].getAttribute("company");
        var address = markers[i].getAttribute("address");
        var city = markers[i].getAttribute("city");

        var zip = markers[i].getAttribute("zip");
        var phone = markers[i].getAttribute("phone");
        var url = markers[i].getAttribute("url");
        var brewery_type = markers[i].getAttribute("type");
        var member_type = '';
        var member_type = markers[i].getAttribute("member_type");
        var offer =  markers[i].getAttribute("offer");


        var html = "<div class='bubble_content'><strong>" + name + "</strong><br />";
        html += address + "<br/>" + city + ", " + state + " " + zip;
        if(url) html += "<br /><br /><a href='http://" + url + "' target='_blank'>Visit Web Site</a></div>";


        //var marker = createMarker(ids, z, title, contentstring);

        var marker = new google.maps.Marker({
            position: z,  
            map: map,
            title: name,
            icon: icon,
            html: html,
            zindex: i
        });

        //Add a listener for every icon click
        google.maps.event.addListener(marker,'click',function(){
            infowindow.setContent(this.html);
            infowindow.open(map,this);
            //map.setZoom(10);
            //map.setCenter(this.getPosition());
            console.log(this);
        });   

        gmarkers[ids] = marker;
        mapMarkers.push(marker);

        if( x && y ){
            //console.log(ids);
            var infowindow = new google.maps.InfoWindow({content: html});
        }
       /* google.maps.event.addListener(marker, 'click', function() {
            console.log('marker clicked');

          });
        */
        //bounds.extend(z);
        //map.fitBounds(bounds);
        }//end check for US states only!        
    } //end for loop


    var mcOptions = {gridSize: 60, maxZoom: 9};
    var markerCluster = new MarkerClusterer(map, mapMarkers, mcOptions); //this is the function that groups the icons into markers


    });
} //End full function to create map

/*
* FUNCTION
*
* click to bring up one icon when clicked from the list.
*/
function myclick(i){
    console.log('clicked a title ' + i);    
    smoothScroll("#primary");   

    var lat = parseFloat(gmarkers[i].position.k);
    var lng = parseFloat(gmarkers[i].position.B);

    console.log(lat);

    map.setCenter({lat: lat, lng: lng});
    map.setZoom(13);
    google.maps.event.trigger(gmarkers[i], 'click');
};


function createMarker(ids, z, title, contentstring){
    console.log('createMarker');
    var marker = new google.maps.Marker({
        position: z,  
        map: map,
        title: title,
        html: contentstring,
        icon: 'http://maps.google.com/mapfiles/ms/icons/orange-dot.png'
    });

    google.maps.event.addListener(marker,'click',function(){
        infowindow.setContent(this.html);
        infowindow.open(map,marker);
    });   

    gmarkers[ids] = marker;
    //console.log(gmarkers[ids]);

};

/*
* FUNCTION findAddress()
*
* given an adress string, zoom the map to the proper state
*/

function findAddress(position) {

    //Let's determind if we have a state (address) or LatLng
    var addressStr = $("#state_select li.active").data('state-id'); 
    if (addressStr != 'Select a State') address = "US State of "+addressStr;

    if(position) {
        var lat = parseFloat(position['latitude']);
        var lng = parseFloat(position['longitude']);
        var latlng = new google.maps.LatLng(lat, lng);
        //console.log(latlng);
    }

    //Now let's geocode - two different cases
    if (geocoder && position) { //If LatLng
        //console.log('near me');
        geocoder.geocode( { 'location': latlng}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
                    if (results && results[0] && results[0].geometry && results[0].geometry.viewport && addressStr!="ON" && addressStr!="INT") {
                        map.fitBounds(results[0].geometry.viewport); //resize map to fit. 
                        map.setZoom(13);
                    }       
                } else {
                    alert("No results found");
                }   
            }
        });       
     } else if (geocoder && address!="") { //If State
        //console.log('by state');
        geocoder.geocode( { 'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
                    if (results && results[0] && results[0].geometry && results[0].geometry.viewport && addressStr!="ON" && addressStr!="INT") {
                        map.fitBounds(results[0].geometry.viewport); //resize map to fit. 
                        map.setZoom(6);
                    }       
                } else {
                    alert("No results found");
                }
            }          
        });
    } else {
        //alert("Geocode was not successful for the following reason: " + status);
    }
}


function downloadUrl(url, callback) {
    var request = window.ActiveXObject ?
            new ActiveXObject('Microsoft.XMLHTTP') :
            new XMLHttpRequest;

    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            request.onreadystatechange = doNothing;
            callback(request, request.status);
        }
    };

    request.open('GET', url, true);
    request.send(null);
}





function doNothing() {}

这里是 link 到 xml 文件.... http://www.straighttothepint.com/wp-content/uploads/wp-google-maps/Google_Map_APIs.xml

我花了几天时间进行 google 搜索和测试代码的不同部分,以至少获得一个基本的 google 地图以通过 xml 文件标记显示...但无济于事 - 任何帮助将不胜感激!! ~干杯

编辑: 一旦我在调用 maps.js 文件之前在页面上包含以下内联脚本,一切都按预期工作。谢谢大家!

<script>

$(document).ready(function(){ 

var latitude = 39.300299;
var longitude = -97.382812;
view_map('./uploads/your_xml_file.xml', latitude,longitude,4);
//scripts to handle mapping are in js/mylibs/map.js.php              
});
 </script>

查看 html 和您在上面提供的代码,我为您构造了一个 fiddle:

http://jsfiddle.net/loanburger/qafsex5x/

我在 fiddle 顶部的 xml 字符串中添加了两个标记。

我基本上解析 xml 这样做:

var markers = $(xml).find("marker");

然后就和你的 for 循环一样了:

  for (var i = 0; i < markers.length; i++) 
  {
    ...
  }

fiddle 会显示标记。