2012-11-07 114 views
8

我試圖創建一個按鈕,將標記添加到顯示的現有谷歌地圖。Javascript和jquery:單擊按鈕時添加Google地圖標記

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 
      }); 

     }   

    }); 

} 

我很新,我希望有人能幫助我。

如果我有這樣的事情,以顯示我的地圖:

$(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? 
}); 

}); 
+0

是的。在內部發出警報,檢查您是否點擊了正確的按鈕 – madhairsilence

+0

那麼它工作?你有什麼錯誤嗎?我建議在'codeAddress'函數之外創建地圖,因爲每次用戶點擊時都不需要創建新地圖,對吧? – Odi

回答

18

你真幸運!

我有一個工作的例子,你想要做什麼:)

看到完整的代碼,並在這裏進行測試: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) 
}) 
+4

狗屎..我很幸運,謝謝! – hellomello

1

HTML在地圖

<div id="map" style="width:100%;height:500px" ></div> 

javascript用於加載地圖和標記

function myMap() { 
    var myCenter = new google.maps.LatLng(28.214461283939166,83.95801313236007); 
    var map_Canvas = document.getElementById("map"); 
    var mapOptions = {center: myCenter, zoom: 14,mapTypeId:google.maps.MapTypeId.HYBRID}; 
    var map = new google.maps.Map(document.getElementById("map"), mapOptions); 
    google.maps.event.addListener(map, 'click', function(event) { 
     document.getElementById("latitude").value = map.getCenter().lat(); 
     document.getElementById("longitude").value = map.getCenter().lng(); 
     place_Marker(map, event.latLng); 

    }); 

    } 
    var marker; 
    function place_Marker(map, location) { 
     if(marker){ 
      marker.setPosition(location); 
     }else{ 
     marker = new google.maps.Marker({ 
     draggable:true, 
     position: location, 
     animation: google.maps.Animation.DROP, 
     map: map 
    }); 
    } 

    var infowindow = new google.maps.InfoWindow({ 
     content: 'Latitude: ' + location.lat() + '<br>Longitude: ' + location.lng() 
    }); 

    infowindow.open(map,marker); 

    }