javascript - 如何通过点击谷歌地图添加标记

标签 javascript google-maps

我想通过点击谷歌地图来添加标记。 我使用此链接 Google map V3 user adding markers

但是这个例子对我没有帮助。 这是我的代码:

<script>
        var locations = <?=$json?>;
        function initialize() {
            addMarker(42.862101,74.610684); // add markers on map
        }

        google.maps.event.addDomListener(window, 'load', initialize);
</script>

从数据库mysql添加标记的函数:

<script>

    function addMarker(x,y){
        var myLatlng = new google.maps.LatLng(x,y);
        var mapOptions = {
            zoom: 8,
            center: myLatlng,
            minZoom: 3
        }
        var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
        var contentString = '<div id="content">'+
            '<div id="siteNotice">'+
            '</div>'+
            '<h1 id="firstHeading" class="firstHeading">Uluru</h1>'+
            '<div id="bodyContent">'+
            '<p><b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a large ' +
            'Heritage Site.</p>'+
            '<p>Attribution: Uluru, <a href="http://en.wikipedia.org/w/index.php?title=Uluru&oldid=297882194">'+
            'http://en.wikipedia.org/w/index.php?title=Uluru</a> '+
            '(last visited June 22, 2009).</p>'+
            '</div>'+
            '</div>';
        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });
        var marker;
        for (var i = 0; i < locations.length; i++) {
            marker = new google.maps.Marker({
                position: new google.maps.LatLng(locations[i]['coord_lat'], locations[i]['coord_lng']),
                map: map
            });
            //something details
            google.maps.event.addListener(marker, 'click', (function(marker, i) {
                return function() {
                    infowindow.setContent(locations[i]['nameid']);
                    infowindow.open(map, marker);
                }
            })(marker, i));
        }
    }
</script>

最佳答案

# Add marker where user clicks map  
var map = new google.maps.Map(document.getElementById("map"), {
    zoom: 5,
    center: new google.maps.LatLng(40.747688, -74.004142),
    mapTypeId: google.maps.MapTypeId.ROADMAP    
});

google.maps.event.addListener(map, 'click', function(e) {        
    var marker = new google.maps.Marker({
        position: e["latLng"],
        title: "Hello world!"
    });       
    marker.setMap(map);
});        

尝试一下 http://jsfiddle.net/4hf78ag7/

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

相关文章:

android - 如何在 Android 中修复 Google map 标记的自定义大小

javascript - 如何优化 KML 坐标中的标记数量?

javascript - 关闭 JavaScript 中的弹出面板

javascript - 如何设计 sweetAlert

JavaScript 比较失败

ios - 在应用程序中使用 Google map 中的转弯导航

javascript - Google Maps API Places Search 获取搜索结果数量

javascript - javascript中的异步回调

javascript - 在 parcel.js 中为部署的网站添加 Autoprefixer 会破坏所有网站样式吗?

javascript - 谷歌地图,在标记信息窗口中显示mysql信息