关闭地理编码循环多个标记变量

时间:2013-07-17 17:52:03

标签: javascript google-maps closures google-maps-markers geocoding

我遇到了谷歌地图的JavaScript问题。

代码构建为使用Lat和long,但我需要将其转换为使用Zipcodes,这意味着我需要实现地理编码。

在下面的代码中,一切都在运作,我试图减少脂肪。

第一个var设置为latLng(基于提供的lat lng。

正下方是我正在努力的代码。我尽可能地减少了它。

我可以进入它,但我无法将结果从中拉出来。

它被包裹在一个函数中,但那部分已经消失,所以我可以最小化我正在看的东西。

它也适用于运行良好的群集。

所以问题是用(latLngRaw)给标记位置(latLng)输入将更改为更好的东西(测试)。

我查看了闭包示例,但我看不到解决方案。似乎有一些触点可以逃避我,可能是因为我限制改变代码(最小代码更改)。

整个代码块在下面但是动作发生在spinnerUp函数

var latlng var标记 var geocoder

是问题。

提前感谢您的帮助,如果我需要澄清一些现有的功能,请告诉我。

var geocoder;
google.load('maps', '3', {
other_params: 'sensor=false'
});

google.setOnLoadCallback(initialize);
geocoder = new google.maps.Geocoder();

var markerClusterer = null;
var map = null;


    function initialize() {
    var center = new google.maps.LatLng(41.252,-96.009);

    var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: center,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var markers = [];
    for (var i = 0; i < data.count; i++) {
    spinnerUp(i);
    }

        function spinnerUp() {

            var data_mapper = data.locationstuff[i];

            var latLng = new google.maps.LatLng(data_mapper.latitude,data_mapper.longitude);

            var geocoder = new google.maps.Geocoder();
            geocoder.geocode( { 'address': data_mapper.zip}, function(results, status) {
                 if (status == google.maps.GeocoderStatus.OK) {
                     var latLngRaw = results[0].geometry.location;
                     alert(latLngRaw);
                     }
                     });






            var boxText = "<div>";
            var boxText = "<img src='http://gdj.gdj.netdna-cdn.com/wp-content/uploads/2012/08/cute-baby-photo-27.jpg' width='75' align='left'/>";
                boxText += data_mapper.title + "<br>" + data_mapper.address + "<br>" + data_mapper.city + ", " + data_mapper.zip;
                boxText += "</div>";

            var iconColorSpecial = "/images/main/HeartDove.png";

            var marker = new google.maps.Marker({position: latLng, icon:iconColorSpecial});

            var infowindow = new google.maps.InfoWindow({
                                                    content: boxText
                                                    ,disableAutoPan: false
                                                    ,maxWidth: 0
                                                    ,pixelOffset: new google.maps.Size(0, 0)            
                                                    ,zIndex: null
                                                    ,closeBoxMargin: "10px 2px 2px 2px"
                                                    ,closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif"
                                                    ,infoBoxClearance: new google.maps.Size(1, 1)
                                                    ,isHidden: false
                                                    ,pane: "floatPane"
                                                    ,enableEventPropagation: false});


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

        var markerCluster = new MarkerClusterer(map, markers);
    }   

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

(更新):这是一个生成的测试数据集(我正在测试第一个受访者的代码建议)。

var data = { "count": 3,"locationstuff": [{"locaid": 1, "title": "test", "address": "545 Ave A ", "city": "Plattsmouth", "state": "NE", "zip": "68048", "longitude": -95.89, "latitude": 41.01, "iconSpecial": 0},{"locaid": 2, "title": "test2", "address": "14100 Crawford St. ", "city": "Boys Town", "state": "NE ", "zip": "68010", "longitude": -96.13, "latitude": 41.25, "iconSpecial": 0},{"locaid": 3, "title": "test3", "address": "1005 South 76th St. ", "city": "Omaha", "state": "NE", "zip": "68114 ", "longitude": -96.03, "latitude": 41.25, "iconSpecial": 0}]}

2 个答案:

答案 0 :(得分:2)

经过洗牌并整理一下后,我最终得到了这个:

var map, 
    geocoder = new google.maps.Geocoder(),
    infoWinOpts = {
        content: null,//added later
        disableAutoPan: false,
        maxWidth: 0,
        pixelOffset: new google.maps.Size(0, 0),
        zIndex: null,
        closeBoxMargin: "10px 2px 2px 2px",
        closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif",
        infoBoxClearance: new google.maps.Size(1, 1),
        isHidden: false,
        pane: "floatPane",
        enableEventPropagation: false
    };

function spinnerUp(data_mapper) {
    infoWinOpts.content = [
        "<div><img src='http://gdj.gdj.netdna-cdn.com/wp-content/uploads/2012/08/cute-baby-photo-27.jpg' width='75' align='left'/>",
        data_mapper.title + "<br>" + data_mapper.address + "<br>" + data_mapper.city + ", " + data_mapper.zip,
        "</div>"
    ].join('');
    var marker = new google.maps.Marker({
        position: data_mapper.latLng
        icon: "/images/main/HeartDove.png"
    });
    var infowindow = new google.maps.InfoWindow(infoWinOpts);
    google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map, this);
    });
    return marker;
}

function initialize() {
    map = new google.maps.Map(document.getElementById('map'), {
        zoom: 10,
        center: new google.maps.LatLng(41.252, -96.009);
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    var markers = [];
    for (var responseCount=0, latLngRaw, i=0; i < data.count; i++) {
        var data_mapper = data.locationstuff[i];
        geocoder.geocode({
            'address': data_mapper.zip
        }, (function(data_mapper) {
            return function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    latLngRaw = results[0].geometry.location;
                    //alert(latLngRaw);
                    data_mapper.latLng = new google.maps.LatLng(latLngRaw.latitude, latLngRaw.longitude);//or something similar
                    markers.push( spinnerUp(data_mapper) );
                }
                responseCount++;
                if(responseCount == data.count) {
                    var markerCluster = new MarkerClusterer(map, markers);
                }
            }
        })(data_mapper));
    }
}
google.maps.event.addDomListener(window, 'load', initialize);

未经测试

有几个棘手的方面:

  • 需要在for循环的每次传递中形成闭包,以捕获data_mapper
  • 需要维护经过测试的responseCount以确定何时致电new MarkerClusterer()

答案 1 :(得分:0)

地理编码是异步的,您需要在回调例程中使用返回的坐标:

geocoder.geocode( { 'address': data_mapper.zip}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
    var latLngRaw = results[0].geometry.location;
    alert(latLngRaw);
  }
});

您可能还需要将参数(i)传递给spinnerUp函数:

function spinnerUp() {
  var data_mapper = data.locationstuff[i];

这可能有用,没有经过测试,没有数据:

var geocoder = new google.maps.Geocoder();

function createMarker(latLng, data_mapper) {
    var boxText = "<div>";
    var boxText = "<img src='http://gdj.gdj.netdna-cdn.com/wp-content/uploads/2012/08/cute-baby-photo-27.jpg' width='75' align='left'/>";
        boxText += data_mapper.title + "<br>" + data_mapper.address + "<br>" + data_mapper.city + ", " + data_mapper.zip;
        boxText += "</div>";

    var iconColorSpecial = "/images/main/HeartDove.png";

    var marker = new google.maps.Marker({position: latLng, icon:iconColorSpecial});

    // these look like arguments to construct an InfoBubble...
    var infowindow = new google.maps.InfoWindow({
         content: boxText
        ,disableAutoPan: false
        ,maxWidth: 0
        ,pixelOffset: new google.maps.Size(0, 0)            
        ,zIndex: null
        ,closeBoxMargin: "10px 2px 2px 2px"
        ,closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif"
        ,infoBoxClearance: new google.maps.Size(1, 1)
        ,isHidden: false
        ,pane: "floatPane"
        ,enableEventPropagation: false});

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

function geocodeAddress(data_mapper, index) {
 geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
       var latLngRaw = results[0].geometry.location;
       createMarker(latLngRaw, data_mapper);
    } else { alert("Geocoder failed: "+status); ]
 });

function spinnerUp(index) {
  var data_mapper = data.locationstuff[index];
  var latLng = new google.maps.LatLng(data_mapper.latitude,data_mapper.longitude);
  geocodeAddress(data_mapper, index);
}

不确定为什么你的“spinnerUp”函数是初始化函数的本地函数。