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

时间:2014-09-10 10:05:00

标签: 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>

1 个答案:

答案 0 :(得分:1)

# 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/