Javascript和Jquery:单击按钮时为Google Maps添加标记

hel*_*llo 9 javascript jquery google-maps google-maps-api-3

我正在尝试创建一个按钮,为显示的现有谷歌地图添加标记.

function initialize()
{
    geocoder = new google.maps.Geocoder();
    codeAddress();
}



function codeAddress()
{
    var image_icon = 'http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png';
    var address = document.getElementById("type_location").value;

    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {

            var mapOptions = {
            zoom: 11,
            center: results[0].geometry.location,
            mapTypeId: google.maps.MapTypeId.ROADMAP
            }

        map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location,
                icon: image_icon
            });

        }           

    });

}
Run Code Online (Sandbox Code Playgroud)

我很新,我希望有人可以帮助我.

如果我有这样的东西来显示我的地图:

$(document).ready(function() {  

var coord = $(".address").attr("data-coordinates"); //this displays lat,lng (example: 32.000,-118.000)

var geocoder;
var map;    
initialize();
$(".add_marker").click(function(){

    // this is where I should add a marker?
});

});
Run Code Online (Sandbox Code Playgroud)

RAS*_*ASG 20

幸运的你!

我有一个工作的例子,它完全符合你的要求:)

查看完整代码并在此处测试:http://jsfiddle.net/RASG/vA4eQ/
只需单击"添加标记"按钮

这是相关代码:

var latlng = new google.maps.LatLng(42.745334, 12.738430);

function addmarker(latilongi) {
    var marker = new google.maps.Marker({
        position: latilongi,
        title: 'new marker',
        draggable: true,
        map: map
    });
    map.setCenter(marker.getPosition())
}

$('#btnaddmarker').on('click', function() {
    addmarker(latlng)
})
Run Code Online (Sandbox Code Playgroud)