如何在标记谷歌地图中添加地址

How to add address in marker google map?

本文关键字:添加 地址 谷歌地图      更新时间:2023-09-26

我的HTML代码是这样的:

<a href="#" class="button" data-latLng="53#separator#-1.33#separator#Address 1">Button 1</a>
<a href="#" class="button" data-latLng="-34.397#separator#150.644#separator#Address 2">Button 2</a>
<div id="map-canvas"></div>

我的Javascript代码是这样的:

$(document).on("click", ".button", function(e) {
    e.preventDefault();
    var latLng = $(this).attr("data-latLng");           
    initialize(latLng);
    function initialize(latLng) {
        console.log(latLng);
        latLng = latLng.split("#separator#");
        address = latLng[2];
        console.log(address);
        var map;        
        var myCenter=new google.maps.LatLng(latLng[0],latLng[1]);
        var marker=new google.maps.Marker({
            position:myCenter
        });
        var mapProp = {
            center: myCenter,
            zoom: 14,
            mapTypeId:google.maps.MapTypeId.ROADMAP
        };
        map=new google.maps.Map(document.getElementById("map-canvas"),mapProp);
        marker.setMap(map);
        ...
    };
    ...
});

演示如下:https://jsfiddle.net/oscar11/b0ahcLxw/

我想在标记谷歌地图中显示地址,但我仍然很困惑。因此,当点击按钮时,地图会自动在标记上显示地址。

有解决我问题的办法吗?

非常感谢

您没有声明infowindowcontentString变量。所以你需要像下面的一样声明infowindow变量

var infowindow = new google.maps.InfoWindow();

并声明contentString

var contentString ="Your Content String";

编辑:

// Add this line
var contentString ="Your Content String";
google.maps.event.addListener(marker, 'click', function() {
    // Add this line
    var infowindow = new google.maps.InfoWindow();
    infowindow.setContent(contentString);
    infowindow.open(map, marker);
}); 

Js投标示例
自动显示信息窗口JsFiddle Demo

添加此行并在helloo的位置设置内容。

google.maps.event.addListener(marker, 'click', function() {
var infowindow = new google.maps.InfoWindow();
infowindow.setContent("hellooo");
infowindow.open(map, marker);
}); 

其他你可以在这里找到JsFiddle

为了从lat-long获取地址,您可以使用反向地理编码你可以在这里找到带有代码的示例试试这个反向地理编码