Reputation: 5142
This is what I want to do: I ask the user to type a latitude+longitude into an input box and I want to show a marker on the map for that location, without having to initialize the map every time.
I have initialized a map as follows:
<script type="text/javascript">
jQuery(document).ready(function() {
var myOptions = {
center: new google.maps.LatLng(34.053228, -118.259583),
zoom: 12,
zoomControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
});
</script>
<div style='height: 400px;'>
<div id="map_canvas" style="width:100%; float: left; height:100%"></div>
</div>
No jazz till now, this is the normal way of defining a map. Now, I have an input box, where I ask the user to type an address:
<input type="text" size=30 name="lat" id="lat">
<input type="text" size=30 name="lon" id="lon">
<button type="button" id="address_submit">Search</button>
I want to show the marker for that address. I defined a function, shown below, but am not getting how to show get the map object:
$("#address_submit").live("click", function() {
lat = $("#lat").val();
lon = $("#lon").val();
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lon),
map: map, //HOW DO I GET THIS MAP OBJECT??
title:"Hello World!"
});
}
Upvotes: 1
Views: 3250
Reputation: 123367
I've tried your code in a jsfiddle => http://jsfiddle.net/HaDbR/ and all seems to work as expected (I've reduced a bit the zoom factor just to see inserted markers): I've inserted some coordinates in the form (near to the map center coords) and the markers appeared correctly.
The only real differences is the visibility of map
variable so that the click
handler applied to the button can see it, and the .on()
method instead of .live()
I've inserted the googlemap API script, calling a callback function createMap()
and in that function I've initialized the map and I've associated the handler, so by closure it can have access to your map
Upvotes: 1