将谷歌地图坐标传递给标记

时间:2014-03-24 14:26:26

标签: javascript forms google-maps google-maps-api-3 marker

我希望传递从两个文本字段(displayLat和displayLong)接收的一组坐标,并创建一个标记,其中传入的坐标作为标记位置。 代码到目前为止:

    <html>
    <head>
    <script>
    function initialize()
    {
    var markersArray = [];          //array to hold the map markers

    function clearOverlays() {      //function to clear the markers from the arrays, deleting them from the map
      for (var i = 0; i < markersArray.length; i++ ) {
markersArray[i].setMap(null);
      }
      markersArray.length = 0;
    }
    var mapProp = {     //the actual map in the page
      center:new google.maps.LatLng(51.8978719,-8.471087399999988),     //center of map
      zoom:12,          //zoom level
      mapTypeId:google.maps.MapTypeId.ROADMAP       //kind of map
      };
    var map=new google.maps.Map(document.getElementById("googleMap")        //element ID
      ,mapProp);

    google.maps.event.addListener(map, 'rightclick', function(event) {      //what happens when the map is right clicked
        clearOverlays();            //removes current markers form the map
      });

    function placeMarker(location) {        //place marker function, adds marker to passed in location
var marker = new google.maps.Marker({
position: location,
map: map,
      })
      markersArray.push(marker);        //adds new marker to the markers array
      google.maps.event.addListener(marker,"click",function(){});           
      ;

    google.maps.event.addListener(marker, 'click', function() {     //listener so when a marker is clicked an infowindow pops up
infowindow.open(map,marker);
      });
    }
    }

    function InputCoords()
    {
    var Inputlat = document.getElementById('displayLat').value;
    var Inputlng = document.getElementById('displayLong').value;
    var newLatLng = new google.maps.LatLng(Inputlat, Inputlng); 

    document.getElementById("button1").innerHTML=newLatLng;

    placeMarker(newLatLng); 

    document.getElementById("button1").innerHTML="Past var dec";

    }

    google.maps.event.addDomListener(window, 'load', initialize);


    </script>
    </head>

    <body>
    <div id="googleMap" style="width:500px;height:380px;"></div>
    Lat 1:<input type="text" size="20" maxlength="50" name="displayLat" id ="displayLat" value=""><br />
    Long 1:<input type="text" size="20" maxlength="50" name="displayLong" id="displayLong" value=""><br />

    <button onclick="InputCoords()">Input Coordinates</button>
    <p id="button1"></p>


    </body>
    </html>

到目前为止,我正在传递坐标,将它们转换为google.maps.LatLng对象,但据我所知,它们没有传递给placeMarker函数。 提前谢谢。

1 个答案:

答案 0 :(得分:1)

函数InputCoords()调用函数placeMarker(),这是不可见的,因为它是initialize()函数的本地函数。你必须把它放在它外面。并将变量mapmarkersArray设为全局。

请参阅example at jsbin

您还可以添加:

map.setCenter(location);

placeMarker()函数可查看标记,如果位置偏离地图的当前可见部分。