Reputation: 15
I am looking to pass a set of coordinates received from two textfields(displayLat and displayLong) and create a marker with the passed in coordinates as the marker location. Code so far:
<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>
So far I am passing in the coordinates, converting them into a google.maps.LatLng object but they are not getting passed to the placeMarker function so far as I can tell. Thanks in advance.
Upvotes: 0
Views: 1367
Reputation: 11258
function InputCoords()
calls function placeMarker()
which is not visible because it is local to initialize()
function. You have to place it out of it. And make variables map
and markersArray
global.
See example at jsbin.
You can also add:
map.setCenter(location);
to placeMarker()
function to see marker if location is off the current visible part of map.
Upvotes: 1