Google Maps api,Place search和Marker Infowidget

时间:2012-09-08 13:30:51

标签: google-maps

我正在使用谷歌地图和谷歌地方搜索,我有两个问题。

1 - 当我们离开标记时,我希望infowidget保持打开状态。这意味着如果该标记已经悬停在上面,所有信息窗口将保持打开状态,此时它会在另一个标记窗口打开时关闭前一个标记窗口。

2 - 我的地方搜索结果很少。例如,在寻找堪萨斯城的麦当劳时,它只给我一个结果。代码在这里。

function initialize() 
{
    var lat;
    var longitude;
    var zoom;
    var radius_hidden=document.getElementById("hidden_radius").value;
    var searchname=document.getElementById("hidden_searchname").value;
    if(trim(document.getElementById("longitude").value)!="")
    {
        zoom=11; 
        lat=document.getElementById("latitude").value;
        longitude=document.getElementById("longitude").value;
    }
    else
    {
        zoom=11;
        longitude="-88";
        lat="42";
    }
    latlng = new google.maps.LatLng(lat,longitude);
    var myOptions = {
      zoom: zoom,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("map"), myOptions);


    //alert("Radius:"+radius_hidden);
    var requestsearch = {
        location: latlng,

        name: searchname,
        types: ['store'],
        bound:latlngbounds,
        rankBy: google.maps.places.RankBy.DISTANCE
    };
    // keyword: searchname,//name: searchname, to get like pages and name to get exact
    service = new google.maps.places.PlacesService(map);
    //service.textSearch(requestsearch, callback);
    service.search(requestsearch, callback);

    if(map != null) {
        google.maps.event.addListener(map, 'drag', function(event) {
            calculateCenter();  
        });
    }
}
google.maps.event.addDomListener(window, 'load', initialize);


google.maps.event.addDomListener(window, 'resize', function() {
  map.setCenter(center);
  //google.maps.event.trigger(map, 'resize');
});
function calculateCenter() {
    var latlngbounds = new google.maps.LatLngBounds();

for (var i = 0 ; i < markersArray.length ; i++) {
     latlngbounds.extend(markersArray[i].getPosition());
}

//map.setCenter(latlngbounds.getCenter(), map.getBoundsZoomLevel(latlngbounds));
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
 center = map.getCenter();
}
    function callAfterMarker(){
  alert("Market Clicked");
}
function callback(results, status)
{
    var listing='<table width="100%" border="0">';
    var num=5;
    markersArray = new Array();
    if (status == google.maps.places.PlacesServiceStatus.OK) 
    {
      for (var i = 0; i < results.length; i++) 
      {
        var pincode='';
        var address='';
        geocoder = new google.maps.Geocoder();
        geocoder.geocode({
          'address': results[i].vicinity,
          'partialmatch': true},function(resultsp, status)
          {
            if (status == 'OK' && resultsp.length > 0) 
            {
                address=resultsp[0].formatted_address;
                var len=resultsp[0].address_components.length-1;
                var res=resultsp[0].address_components[len].short_name;
                if(res!=undefined)
                {
                    //address+="<br>Pincode:"+res.toString();
                }
                //listing+='<tr><td>Zip Code: '+res.toString()+'</td></tr>';
            } 
        });

        marker = new google.maps.Marker({
            position: results[i].geometry.location,
            title: results[i].name,
            zIndex: 2,
            icon: gicons["blue"]
        });
        infowindow = new google.maps.InfoWindow();
        google.maps.event.addListener(marker, 'click', (function (marker, i) {
            return function () {
                var contentString = '<div id="infowindow' + i + '"><table width="100%"><tr><td>'+results[i].name+'</td></tr><tr><td style="word-wrap: break-word;">'+getaddress(results[i].vicinity)+'</td></tr><?php if(trim($finalURL)){ echo "<tr><td align=\"center\"><a target=\"_blank\" class=\"sty-action-buttn\" href=\"".$finalURL."\">".trim(getFieldFromDB('user_config','BubbleText'))."</a></td></tr>"; }else if(trim(getFieldFromDB('user_config','ActionLink'))){ echo "<tr><td align=\"center\"><a target=\"_blank\" class=\"sty-action-buttn\" href=\"".trim(getFieldFromDB('user_config','ActionLink'))."\">".trim(getFieldFromDB('user_config','BubbleText'))."</a></td></tr>"; }?></table></div>';
                infowindow.setContent(contentString);
                infowindow.open(map, marker);
            }
        })(marker, i));

        google.maps.event.addListener(marker, 'mouseover', (function (marker, i) {
            return function () {
            var contentString = '<div id="infowindow' + i + '"><table width="100%"><tr><td>'+results[i].name+'</td></tr><tr><td style="word-wrap: break-word;">'+getaddress(results[i].vicinity)+'</td></tr><?php if(trim($finalURL)){ echo "<tr><td align=\"center\"><a target=\"_blank\" class=\"sty-action-buttn\" href=\"".$finalURL."\">".trim(getFieldFromDB('user_config','BubbleText'))."</a></td></tr>"; }else if(trim(getFieldFromDB('user_config','ActionLink'))){ echo "<tr><td align=\"center\"><a target=\"_blank\" class=\"sty-action-buttn\" href=\"".trim(getFieldFromDB('user_config','ActionLink'))."\">".trim(getFieldFromDB('user_config','BubbleText'))."</a></td></tr>"; }?></table></div>';
            var listItem = document.getElementById("item-" + i);
            listItem.className = "grey";
               infowindow.setContent(contentString);
                infowindow.open(map, marker);

            }

        })(marker, i));

              google.maps.event.addListener(marker, 'mouseout', (function (marker, i) {
            return function () {

        /*var contentString = '<div id="infowindow' + i + '"><table width="100%"><tr><td>'+results[i].name+'</td></tr><tr><td style="word-wrap: break-word;">'+getaddress(results[i].vicinity)+'</td></tr><?php if(trim($finalURL)){ echo "<tr><td align=\"center\"><a target=\"_blank\" class=\"sty-action-buttn\" href=\"".$finalURL."\">".trim(getFieldFromDB('user_config','BubbleText'))."</a></td></tr>"; }else if(trim(getFieldFromDB('user_config','ActionLink'))){ echo "<tr><td align=\"center\"><a target=\"_blank\" class=\"sty-action-buttn\" href=\"".trim(getFieldFromDB('user_config','ActionLink'))."\">".trim(getFieldFromDB('user_config','BubbleText'))."</a></td></tr>"; }?></table></div>';*/
            var listItem = document.getElementById("item-" + i);
            listItem.className = "change";
             marker.setIcon(gicons["blue"]);
             /* infowindow.setContent(contentString);
                infowindow.open(map, marker);*/

            }

        })(marker, i));

        markersArray.push(marker);
        calculateCenter();
        listing+='<tr><td>';

        var address_link=results[i].vicinity.replace(" ","+");
        if(i==0)
        {
            listing+='<table id="div5" width="100%" >'; 
        }
        else if(i%5==0)
        {
            num+=5;
            listing+='<table id="div'+num+'" class="myclass" style="display:none;" width="100%">';  
        }
        //'+results[i].name+'
        listing +='<tr id="searchadd"><td ><input type="hidden" value="'+results[i].name+'" name="end'+i+'" id="end'+i+'"></td></tr><tr><td style="word-wrap: break-word;border-bottom:1px solid #cccccc;" onmouseout="markersArray['+i+'].setIcon(gicons.blue)" onmouseover="markersArray['+i+'].setIcon(gicons.yellow);openInfoWindow('+i+')"      class="" id="item-'+i+'">'+getaddress(results[i].vicinity)+'<div id="spacer" style="width:120px;height:1px;float:left;"></div><a   style="width:100px;height: 20px;" class="sty-hyperlink" target="_blank" href="https://maps.google.com/maps?daddr='+address_link+'"><b><?php echo getFieldFromDB('user_config','DirectionText'); ?></b></a><br></td></tr>';

        if(i ==(results.length-1))
        {
            listing+='</table>';
            listing+='<span id="largerwindowlink"><br><a  target="_blank" class="sty-action-buttn" href="http://www.franchiseportals.com/contact.php?id=<?php echo $finalURL; ?>"><?php echo trim(getFieldFromDB('user_config','ActionButtonText')); ?></a></span>';
        }
        else if(i>0 &&(i+1)%5==0)
        {
            listing+='<tr><td align="right"><a class="sty-hyperlink" style="width:100px;height: 20px;" href="javascript:void(0);" onclick="javascript:show_hide_table('+num+');" ><b><?php echo getFieldFromDB('user_config','MoreResultText'); ?></b></a></td></tr></table>';
        }
        listing+='</td></tr>';
      }
      showOverlays(5);
      listing +='</table>';
      if(results.length<=0)
      {
            listing='<br><br><span style="color:green;">Sorry! No stores found.<br>Please try another franchise name</span><br><br>';
      }
    }
    else
    {
        listing='<br><br><span style="color:green;">Sorry! No stores found.<br>Please try another franchise name</span><br><br>';
    }
    document.getElementById("listingAddress").innerHTML=listing;
}
function showOverlays(no) 
{
    if (markersArray) 
    {
        for (i in markersArray) 
        { 
            if(i<no && i>=no-5)
                markersArray[i].setMap(map);
        }
    }
}
function clearOverlays() 
{
    if (markersArray) 
    {
        for (i in markersArray) 
        {
                markersArray[i].setMap(null);
        }
    }
}
function openInfoWindow(loopID)
{
    google.maps.event.trigger(markersArray[(parseInt(loopID))], "click");
}     
function show_hide_table(tablid)
{
    var showid=tablid+5;
    clearOverlays();
    showOverlays(showid);
    if(document.getElementById("div"+showid))
    {
        document.getElementById("div"+showid).style.display="block";
    }
    if(document.getElementById("div"+tablid))
    {
        document.getElementById("div"+tablid).style.display="none"; 
    }
}
function checkPin()
{
    if(document.getElementById("pincode").value=="" || trim(document.getElementById("pincode").value)=="" )
    {
    alert("Please fill the Zip Code");
    document.getElementById("pincode").focus();
    return false;
    }
}
function checkMobPin()
{
    if(document.getElementById("zipcode").value=="" || trim(document.getElementById("zipcode").value)=="Choose other zip code" )
    {
        alert("Please fill the Zip Code");
        document.getElementById("zipcode").focus();
        return false;
    }
    else
    {
        document.getElementById("pincode").value=document.getElementById("zipcode").value;
    }
}
function show_table()
{
    if (document.getElementById("viewOption").value == "list") 
    {
        document.getElementById("maptd").className = "list-map-td-change";
        document.getElementById("addresstd").className="list-address-td-change";
    }
    else
    {
        document.getElementById("maptd").className="list-map-td";
        document.getElementById("addresstd").className="list-address-td";
    }
}
function getaddress(address)
{
    var part=address.split(',');
    var result='';
    for(var i=0; i<part.length; i++)
    {
        result+=part[i]+'<br>'  ;
    }
    return result;
}
//alert($(window).width());
/*$(window).resize(function() {
    if($(window).width()<=600)
        map.setZoom(10);
    if($(window).width()>600)
        map.setZoom(11);
        google.maps.event.trigger(map, 'resize');
});*/

</script>
<script>
$(function() {
    function log( message ) {
        $( "<div/>" ).text( message ).prependTo( "#log" );
        $( "#log" ).attr( "scrollTop", 0 );
    }
        $( "#address" ).autocomplete({              //here you have to write the name of search box, no need to call function from textbox
            source: "jquery4dd/search_content.php",
            minLength: 1,
            selectFirst:true,
            select: function(event, ui) {
                    $('#business_url').val(ui.item.url);
                    $('#address').val(ui.item.value);
               }
        });

});
function checkAddress()
{
  if(document.getElementById("address").value=="" || trim(document.getElementById("address").value)=="Type Name Here" )
  {
    alert("Please fill the Business Name");
    document.getElementById("address").focus();
    return false;
  }
}

编辑: 您可以在此处查看搜索麦当劳的结果My site。您还可以在网址中查看要传递给查询的参数。

1 个答案:

答案 0 :(得分:2)

  1. 实际上,对于所有标记,您只有1个infoWindow对象,每个标记需要1个。 用以下内容替换callback - 函数的mouseover-and-click-part:

    window.zIndex= window.zIndex||100;
    google.maps.event.addListener(marker, 'mouseover', (function (marker, i,infowindow) {
        return function () {
            var contentString = '<div id="infowindow' + i + '"><table width="100%"><tr><td>'+results[i].name+'</td></tr><tr><td style="word-wrap: break-word;">'+getaddress(results[i].vicinity)+'</td></tr><tr><td align="center"><a target="_blank" class="sty-action-buttn" href=" http://www.franchiseopportunities.com/franchisefbo.asp?fboid=">Get More Information</a></td></tr></table></div>';
            infowindow.setContent(contentString);
                 //brings the infoWindow into front
            infowindow.setZIndex(window.zIndex++);
            infowindow.open(map, marker);
        }
    })(marker, i, new google.maps.InfoWindow()));
    
  2. 可能有争议:D,但麦当劳不是一家餐馆,而是一家商店,你应该把类型换成“餐馆”