0

我在一张地图上有很多标记,在 for 循环中添加。我设法使 infoWindows 按预期显示,但我有一个问题 - 单击关闭按钮时它们不会关闭。如果我打开一个新的,旧的会关闭,这很好。当用户点击地图上的其他任何地方时,我什至设法让它关闭。我一直在寻找解决方案,但我没有找到任何东西。理想情况下,我想让关闭按钮工作,但我想如果我可以隐藏它就足够了。

这是一些代码:

添加标记:

function addMarker( map, lat, lon, title, center, image, link )
{
// create latlng object
var latLng = new google.maps.LatLng( parseFloat( lat ), parseFloat( lon ) );
// set image base URL
var imageBase = ajax_vars.home_url + '/images/map-markers/';
// set default image
if ( typeof( image ) == 'undefined' )
    image = 'default';

// CREATE MAPS OBJECTS FOR THE MARKER
// main image
var icon = new google.maps.MarkerImage(
    imageBase + image + '.png',
    new google.maps.Size(32, 32),
    new google.maps.Point(0,0),
    new google.maps.Point(0, 32)
);
// shadow
var shadow = new google.maps.MarkerImage(
    imageBase + image + '.shadow.png',
    new google.maps.Size(32, 32),
    new google.maps.Point(0,0),
    new google.maps.Point(0, 32)
);
// shape
var shape = {
    coord: [1, 1, 1, 32, 32, 32, 32 , 1],
    type: 'poly'
};

// ADD MARKER
marker = new google.maps.Marker({
    position: latLng,
    title: title,
    map: map,
    shadow: shadow,
    icon: icon,
    shape: shape
}); 

// ADD INFOWINDOW TO MARKER
addInfoWindowToMarker( marker, title, link );

// CENTER MARKER IF REQUIRED
if ( center )
    map.setCenter( latLng );    

}

添加信息窗口:

function addInfoWindowToMarker( marker, title, link )
{
    // WINDOW HTML CONTENT
    // link html
    if ( typeof( link ) == 'undefined' )
        link = '';
    else
        link = "(<a href='" + link + "'>click to view</a>)";
    // window html
    var htmlContent = "<div class='infoWindow'>This is content for " 
        + title 
        + "<br/>"
        + link
        + "</div>"

    // create object
    infowindow = new google.maps.InfoWindow();


    // CLICK EVENT LISTENER
    google.maps.event.addListener( marker, 'click', function() {
        infowindow.setContent( htmlContent ),
        infowindow.open( map, marker ),
        // trying to hide the button
        // $( '.infoWindow' ).parent().parent().siblings().find( 'img' ).hide();
        //$( '[src="http://maps.gstatic.com/mapfiles/mv/imgs8.png"]' ).hide();
    });

    // trying to close the winddow on click
    google.maps.event.addListener(  infowindow, 'closeclick', function(){       
        infowindow.open( null, null ); 
        alert('closing');
    });
}

当我单击按钮时,甚至不会触发 closeclick 事件。隐藏按钮的尝试什么也没做。

单击标记时出现我不明白的错误:未捕获的类型错误:对象#没有方法“M”

你可以在这里查看地图。

4

3 回答 3

1

我遇到了类似的事情:关闭按钮没有导致 infoWindow 关闭。在我的例子中,map 参数的值不是正确的元素(它是一个包装器/容器)。

一旦我通过了正确的元素,一切都按预期工作。

于 2013-02-14T18:39:28.000 回答
0

乍一看,您在单击处理程序中使用的是逗号而不是分号:

google.maps.event.addListener( marker, 'click', function() {
        infowindow.setContent( htmlContent ), ---> HERE
        infowindow.open( map, marker ), ---------> AND HERE

尝试将那些替换为分号;,因为这可能是您遇到的错误。

更新:
在您的 infowindowcloseclick处理程序中,替换您的以下行:

infowindow.open( null, null ); 

对于这个:

infowindow.close();

close()通常用于关闭信息窗口的方法一样。

于 2012-12-13T12:03:06.903 回答
0

请参考我已经使用过的以下示例。

第 1 步:在页面标题中包含三个脚本文件。例如

(i). <script type="text/javascript" src="http://maps.google.com/maps?file=api&v=2&key=Your_API_KEY"></script>
(ii).<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
(iii).<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js"></script>

步骤#2:页面上的脚本

<script type="text/javascript">

//initialize the map window

jQuery(document).ready(function () {
    load();
});

jQuery(window).unload(function () {
    GUnload();
});

    var map;
    var geocoder;
    var directionDisplay;
    var directionsService = new google.maps.DirectionsService();

    function load() {
        if (GBrowserIsCompatible()) {
            geocoder = new GClientGeocoder();
            map = new GMap2(document.getElementById('map'));
            map.addControl(new GSmallMapControl());
            map.addControl(new GMapTypeControl());
            //map.setCenter(new GLatLng(35.048629,-0.820663), 4);
            searchLocations();
            document.getElementById('directions-panel').innerHTML = '';
            var url_new = ''+ benObj.TEMPLATE_DIR +'/print.html';
            var print_icon_url_new = '<a href="javascript:void(0);" class="print" onClick="window.open(\'' + url_new + '\');">Print</a><a href="#" class="link">Link</a>';
            jQuery('#print_icon').html(print_icon_url_new);
        }
    }


//Search Locations with address input

 function searchLocations() {

        var address = document.getElementById('addressInput').value;
        // alert(address);
        var address_new = jQuery("#addressInput_new").val();
        if (address_new != "Enter City or Zip") {
            jQuery("#loc1").html(address_new);
        }
        geocoder.getLatLng(address, function (latlng) {
            //alert(latlng);
            if (!latlng) {
                alert(address + ' not found');
            } else {
                searchLocationsNear(latlng);
            }
        });

    }


// Search Near By Location to place the Markers and Information windows

function searchLocationsNear(center) {
        var radius = document.getElementById('radiusSelect').value;
        var searchUrl = ''+ benObj.BASE_ROOT +'/mapmarker?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius + '&format=raw';


        jQuery.get(searchUrl, function (data) {

            var xml = GXml.parse(data);


            var markers = xml.documentElement.getElementsByTagName('marker');
            map.clearOverlays();

            var sidebar = document.getElementById('sidebar');
            var sidebar_val = '';
            //sidebar.innerHTML = 'Results Found';
            jQuery("#sidebar").html(sidebar_val);

            <!--jQuery("#loc_count").html(markers.length);-->


            if (markers.length == 0) {
                sidebar.innerHTML = 'No results found.';
                map.setCenter(new GLatLng(35.048629, -0.820663), 4);
                return;
            }

            var bounds = new GLatLngBounds();
            for (var i = 0; i < markers.length; i++) {
                var name = markers[i].getAttribute('name');
                var address = markers[i].getAttribute('address');
                var phone_new = markers[i].getAttribute('phonenumber');
                var distance = parseFloat(markers[i].getAttribute('distance'));
                var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')), parseFloat(markers[i].getAttribute('lng')));
                var markerchar = "b";
                var marker = createMarker(point, name, address, phone_new);
                map.addOverlay(marker);
                // var location_count = jQuery('#loc_count').val();
                jQuery('#loc_count').val(i + 1);

                var sidebarEntry = createSidebarEntry(marker, name, address, distance, phone_new);

                jQuery('#sidebar').append(sidebarEntry);


                //sidebar.appendChild(sidebarEntry);

                //  ScrollPane.getContentPane().appendChild(sidebarEntry);
                bounds.extend(point);

            }
            map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
            jQuery('#sidebar').jScrollPane();
            //jQuery('#sidebar').reinitialise();

        });

    }

//To Create a Marker With Information Window

 function createMarker(point, name, address, phone_new) {

        var pinkIcon = new GIcon(G_DEFAULT_ICON);
        pinkIcon.image = ""+ benObj.IMAGE_DIR +"addr-pin-1.png";
        var markerOptions = {
            icon: pinkIcon
        };


        var marker = new GMarker(point, markerOptions);
        var event_calendar = "event_calendar";
        var event_title = ""+ benObj.event_title +"";
        var display = "block";
        var e_dt_start = jQuery("#dtstart").val();
        var e_dt_end = jQuery("#dtend").val();
        var e_start_timestamp = (formatTimestring(e_dt_start));
        var e_end_timestamp = (formatTimestring(e_dt_end));
        var e_desc = jQuery("#edesc").val();
        var StrippedString = e_desc.replace(/(<([^>]+)>)/ig, "");
        var trimmed = StrippedString.replace(/^\s+|\s+$/g, '');
        var html = '<b>' + name + '</b> <br/>' + address + '<br>contact: ' + phone_new + '<br><br><a href="javascript:void(0);" style="text-decoration:none;" onclick="addtocalender();" class="addtocal" id="add_to_cal">Add to Calendar<div class="summary" style="display:none;">' + event_title + ' - "' + name + '"</div><span class="dtstart date" title="' + e_dt_start + '" style="display:none;">8th Aug 2010</span><span class="dtend date" title="' + e_dt_end + '" style="display:none;">01:30am - 12:00pm</span><div class="event-desc" style="display:none;">' + trimmed + '</div><div class="event-locate" style="display:none;">' + name + ',' + address + '</div></a>&nbsp;|&nbsp;<a href="javascript:void(0);" style="text-decoration:none;">Remind Me</a><br><br>Get Direction From:<br><input type="hidden" id="start" value="' + address + '"><input type="text" id="end" value="" style="border: 1px solid #ECE6D5;">&nbsp;<input type="button" value="GO" onclick="calcRoute();" style="border: 1px solid #ECE6D5;padding-left:5px;">';
        GEvent.addListener(marker, 'click', function () {
            marker.openInfoWindowHtml(html);

            //jQuery(this).addtocal();
        });
        return marker;
    }

// To Make Sidebar Entry If need

 function createSidebarEntry(marker, name, address, distance, phone_new) {
        var div = document.createElement('div');
        var html = '<div class="locrow clearfix"><div class="left" style="width:240px;"><span class="count" id="loc_count">' + jQuery("#loc_count").val() + '</span><address><strong>' + name + '</strong>' + address + '</address><span class="mapdate"><span class="icon date"></span>'+ benObj.event_start_month_date +' &ndash; '+ benObj.event_end_month_date_year +'</span></div><div class="right" style="width:154px;"><ul><li><span class="icon phone"></span>' + phone_new + '</li><li><span class="icon time"></span>11 am &ndash; 7 pm</li><li><span class="icon car"></span>distance ' + distance.toFixed(1) + ' mi</li></ul></div></div>';

        div.innerHTML = html;
        div.style.cursor = 'pointer';
        div.style.marginBottom = '5px';
        GEvent.addDomListener(div, 'click', function () {
            GEvent.trigger(marker, 'click');
        });
        GEvent.addDomListener(div, 'mouseover', function () {
            div.style.backgroundColor = '#eee';
        });
        GEvent.addDomListener(div, 'mouseout', function () {
            div.style.backgroundColor = '#fff';
        });
        return div;
    }

// To make a Directions If need

function calcRoute() {
        directionsDisplay = new google.maps.DirectionsRenderer();
        var start = document.getElementById('start').value;
        var end = document.getElementById('end').value;
        var url = "http://maps.google.co.in/maps?f=d&source=s_d&saddr=" + start + "&daddr=" + end + "&aq=0&vpsrc=0&hl=en&doflg=ptm&mra=ls&ie=UTF8&t=m&z=5&layer=c&pw=2";
        var print_icon_url = '<a href="javascript:void(0);" class="print" onClick="window.open(\'' + url + '\');">Print</a><a href="#" class="link">Link</a>';

        var request = {
            origin: start,
            destination: end,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        directionsService.route(request, function (response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                var myOptions = {
                    zoom: 7,
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    center: new google.maps.LatLng(41.850033, -87.6500523)
                };
                map = new google.maps.Map(document.getElementById('map'), myOptions);
                directionsDisplay.setMap(map);
                directionsDisplay.setPanel(document.getElementById('directions-panel'));
                directionsDisplay.setDirections(response);
                jQuery('#print_icon').html(print_icon_url);
            }
        });
    }

</script>

步骤 #3:为标记和信息窗口创建 XML

<?php
function mapMarker($center_lat,$center_lng,$radius)
    {
    $mysqli = $this->_getMySqlConnection();
    // Start XML file, create parent node
    $dom        =   new DOMDocument("1.0");
    $node       =   $dom->createElement("markers");
    $parnode    =   $dom->appendChild($node);

    // Search the rows in the markers table
    $query      =   sprintf("SELECT phone,street_address_1, store_name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM locations HAVING distance < '%s' ORDER BY distance LIMIT 0 , 10",
    $mysqli->real_escape_string($center_lat),
    $mysqli->real_escape_string($center_lng),
    $mysqli->real_escape_string($center_lat),
    $mysqli->real_escape_string($radius));

    $result = $mysqli->query($query);

    header("Content-type: text/xml");
    header('Access-Control-Allow-Origin: *');

    $avoid_duplicate="";
    // Iterate through the rows, adding XML nodes for each
        while ($row = @$result->fetch_assoc())
        {
            if($avoid_duplicate!=$row['store_name'])
            {
            $node = $dom->createElement("marker");
            $newnode = $parnode->appendChild($node);
            $newnode->setAttribute("name", $row['store_name']);
            $newnode->setAttribute("address", $row['street_address_1']);
            $newnode->setAttribute("lat", $row['lat']);
            $newnode->setAttribute("lng", $row['lng']);
            $newnode->setAttribute("distance", $row['distance']);
            $newnode->setAttribute("phonenumber", $row['phone']);
            $avoid_duplicate=$row['store_name'];
            }
        }

    $outXML=$dom->saveXML();
    $result->close();           
    $mysqli->close();
    return $outXML;
    }
?>

第 4 步: HTML 部分

<div class="mapleft">
   <div class="ScrollPane scroll-pane" id="sidebar" style="overflow: auto; height: 430px;"></div>
   <div class="mapshadow"></div>
</div>
    <input type="hidden" id="addressInput" value="<?php echo $zip_code;?>" />
    <input type="hidden" id="radiusSelect" value="50" />
    <input type="hidden" id="addressInput_temp" value="<?php echo $zip_code;?>" />
    <input type="hidden" id="radiusSelect_temp" value="50" />
    <input type="hidden" name="X_REQUESTED_WITH" value="XMLHttpRequest" />
<div class="mapright">
<div id="map" style="width: 475px; height: 450px"></div>
</div>
<div class="map-dir" id="directions-panel" style="float:right;width:488px;"></div>
<input type="hidden" id="loc_count" value="1" />

这些都是会产生伟大成果的东西。我认为这可以帮助您解决问题。

于 2012-12-13T12:36:12.167 回答