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

标签 javascript jquery html google-maps google-maps-api-3

我的 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/

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

有什么办法可以解决我的问题吗?

非常感谢

最佳答案

您没有声明 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);
}); 

JsFiddle Example
自动显示信息窗口 JsFiddle Demo

关于javascript - 如何在标记谷歌地图中添加地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36685170/

相关文章:

javascript - 无法打开触发框

javascript - 如何在 ember 中获取组件的值?

javascript - 具有响应和 http 方法的 Node JS 变量范围

Javascript 未加载我认为 xampp 阻止了它

javascript - 选择器并迭代 Div 内的表

javascript - 检查是否选择了选项 - 具有多个选择

css - html 右对齐列

html - 尝试使用 flexbox 在同一行显示两个无序列表

javascript - 未捕获的类型错误 : Cannot read property 'message' of undefined

javascript - GULP tap.js - 无法读取属性