javascript 当用户将鼠标悬停在地址上时,如何显示弹出式 Google 地图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5418504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:08:24  来源:igfitidea点击:

How can I have a popup Google Map appear when the user hovers over an address?

javascriptgoogle-mapspopup

提问by froadie

I want to set up my site so that whenever a user hovers over an address, a small google map of that address pops up. I've been reading through the Google Maps API documentation, but I'm having a hard time finding a simple way to implement this. It seems I have to use what google calls "geocoding" to find the latitude and longitude based on the address... This is the test page I have so far:

我想设置我的网站,以便每当用户将鼠标悬停在地址上时,就会弹出该地址的小型谷歌地图。我一直在阅读 Google Maps API 文档,但我很难找到一种简单的方法来实现它。看来我必须使用谷歌所说的“地理编码”来根据地址找到经纬度......这是我迄今为止的测试页面:

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
        <style type="text/css">
          html { height: 100% }
          body { height: 100%; margin: 0px; padding: 0px }
          #map_canvas { height: 100% }
        </style>
        <script type="text/javascript"
            src="http://maps.google.com/maps/api/js?sensor=false">
        </script>
        <script type="text/javascript">
            var geocoder;
            var map;

            function codeAddress(address) {
                geocoder = new google.maps.Geocoder();
                geocoder.geocode( { 'address': address}, function(results, status) {
                  if (status == google.maps.GeocoderStatus.OK) {
                    var myOptions = {
                      zoom: 20,
                      center: results[0].geometry.location,
                      mapTypeId: google.maps.MapTypeId.SATELLITE
                    }
                    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
                  } else {
                    alert("Geocode was not successful for the following reason: " + status);
                  }
                });
            }
        </script>
    </head>
<body>
    <div onMouseOver="codeAddress('1405 Harrison Street, Oakland, CA')">
        1405 Harrison Street, Oakland, CA
    </div>
    <div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>

This, however, causes the map to show up in the map_canvas div... What I really want is to make the map show up as a little popup, sort of like a tooltip. How can I accomplish this? Also, how can I set it up so that when the user mouses-out, the map disappears?

然而,这会导致地图显示在 map_canvas div 中......我真正想要的是让地图显示为一个小弹出窗口,有点像工具提示。我怎样才能做到这一点?另外,我如何设置它以便当用户鼠标移开时地图消失?

I'm using html and javascript so far, and my website is in coldfusion.

到目前为止,我正在使用 html 和 javascript,我的网站处于冷融合状态。

回答by Hacknightly

What you'll want to do is set the CSSfor your map_canvas div to display:none. This way, you'll have complete control over when it's actually shown by using javascript. Once you've done that, it's just a matter of targeting the hoverevent for your mouseover div. You'll probably want to do something like this. First make sure you give your mouseover divan onmouseoutevent

您要做的是将CSS您的 map_canvas div 设置为display:none. 这样,您就可以完全控制使用 javascript 实际显示的时间。完成此操作后,只需hover为鼠标悬停 div定位事件即可。你可能想要做这样的事情。首先确保你给你的鼠标悬停div一个onmouseout事件

<div onMouseOver="codeAddress('1405 ...)" onMouseOut="hideMap()" >

</div>

Next, target and show the divwithin your codeAddressfunction like so.

接下来,像这样div在您的codeAddress函数中定位并显示。

function codeAddress(address) {
                geocoder = new google.maps.Geocoder();
                geocoder.geocode( { 'address': address}, function(results, status) {
                  if (status == google.maps.GeocoderStatus.OK) {
                    var myOptions = {
                      zoom: 20,
                      center: results[0].geometry.location,
                      mapTypeId: google.maps.MapTypeId.SATELLITE
                    }
                    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

                     // here's where you would want to show your map
                     // just use javascript to set the display style to block
                    document.getElementById("map_canvas").style.display = 'block'

                  } else {
                    ... [code here]
                  }
                });
            }

Clearly, you'll also want to hide the map upon leaving the div, so your hideMapfunction will do just that.

显然,您还希望在离开 div 时隐藏地图,因此您的hideMap函数将做到这一点。

function hideMap(){
 document.getElementById('map_canvas').style.display = 'none'
}

I know this doesn't implement your ideal 'tooltip' scenario, however I hope this can get you started. Have a look at this tooltip library. I've used it before, and it makes it very simple to turn any div into a tooltip. From there, you should be golden. Happy coding!

我知道这并没有实现您理想的“工具提示”场景,但是我希望这可以帮助您入门。看看这个工具提示库。我以前用过它,它使将任何 div 变成工具提示变得非常简单。从那里,你应该是金色的。快乐编码!

回答by owook

Style the map_canvas to have a border and look like a separate window.
On the mouseover change the map_canvas(or whatever iframe you want to stick it in) x,y to match the mouseOver x,y.
Set mapcanvas.style.display = "none"; on mouseout

将 map_canvas 设置为具有边框并看起来像一个单独的窗口。
在鼠标悬停时更改 map_canvas(或您想要将其插入的任何 iframe)x,y 以匹配 mouseOver x,y。
设置 mapcanvas.style.display = "none"; 鼠标移开时

回答by jamietelin

You could accomplish a popup-window on mouse over quite easy using some jQuery.

您可以使用一些 jQuery 轻松完成鼠标悬停的弹出窗口。

Check out the following jQuery function:

查看以下 jQuery 函数:

http://api.jquery.com/mouseover/

http://api.jquery.com/mouseover/

Idea being that you do something like:

想法是你做这样的事情:

<div id="adress1" style="position:relative;">
    72 MacDougal Street, New York, United States
    <div id="map_for_adress1" style="display:none; position:absolute; top:0; left:0;">
        <!--GOOGLE MAP, DIV for DATA or EMBED CODE-->
    </div>
</div>

<script type="text/javascript">
$("#adress1").mouseover(function() {

    //When mouse is over...
    $('#map_for_adress1').show(0);

  }).mouseout(function(){

    //When mouse is not over...
    $('#map_for_adress1').hide(0);

  });
</script>

Also, why do you need to use the full Google Maps API to show a map of an adress? Why not just the embed-function?

另外,为什么需要使用完整的 Google Maps API 来显示地址地图?为什么不只是嵌入功能?

Something like:

就像是:

<iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=72 MacDougal Street, New York, United States&iwloc=A&output=embed&ie=UTF8"></iframe>

回答by Haochi

Building on Banx's solution, I modified the script as follows:

基于 Banx 的解决方案,我修改了脚本如下:

(function(){
  var geocoder = new google.maps.Geocoder(),
      map = window.map = new google.maps.Map(document.getElementById("map_canvas"), {
          zoom: 16,
          center: new google.maps.LatLng(38.92, -77.06),
          mapTypeId: google.maps.MapTypeId.ROADMAP
        }),
      canvas = $("#map_canvas");

  $(".address").hover(function(){
    canvas.css({
      top: $(this).position().top,
      left: $(this).position().left
    }).show();
    geocoder.geocode( { 'address': $(this).text() }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
          map.fitBounds(results[0].geometry.bounds);
      } else {
        // alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }, function(){
    canvas.hide();
  });
})();

I used jQuery for handling some DOM stuff there but it should be very easy to change it to whatever library (or not) that you are using. The main difference from Banx's code is it reuses the mapand geocoderobjects instead of recreating it every time. Also I am using the boundsfrom the result instead of locationbecause it's more desirable in my opinion.

我使用 jQuery 来处理那里的一些 DOM 内容,但是将它更改为您正在使用的任何库(或不使用)应该非常容易。与 Banx 代码的主要区别在于它重用mapgeocoder对象,而不是每次都重新创建它。此外,我使用boundsfrom 结果而不是location因为在我看来它更可取。