click listeners conflict w/ infowindow - google-maps-api-3

I'm attempting to create a map that allows users to report a trailwork
problem by clicking and filling a form in an infowindow (similar to
seeclickfix.com). I haven't built in the php/SQL that will actually
save the information provided by the user yet.
The problem: I have a button in the html of my infowindow for users to
submit information and close the window. Instead of just closing the
window though, my event listener for new markers receives clicks
through the infowindow, creating an unwanted marker behind the button.
Google avoids this problem somehow; no click is registered on their
top right-exit 'x'.
I've attempted to create a Boolean signal variable ('infopen') to let
my addMarker function know if an infowindow is open, but it's not
functioning.... Any ideas why?
Any other suggestions regarding the code would be appreciated!
(My task is creating a system to organizing and store multiple
infowindows/markers...)
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test Reporter </title>
<script type="text/javascript" src="http://maps.google.com/maps/
api/js?sensor=false"></script>
<script type="text/javascript">
var map;
var marker;
var markers = [];
var infowindow;
var infopen = false;
var edit = true;
var pos = new google.maps.LatLng(44.021, -71.831102);
function initialize() {
var mapOptions = {
zoom: 14,
center: pos,
mapTypeControl: true,
panControl: false,
zoomControl: true,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
var table = "<table>" +
"<tr><td>Problem:</td> <td><input type='text'
id='prob'/> </td> </tr>" +
"<tr><td>Description:</td> <td><input type='text'
size='30' id='desc'/></td> </tr>" +
"<tr><td align=right ><input type='button'
value='Save & Close' onclick='saveData()' /></td>" +
"<td><input type='button' value='Cancel & Delete'
onclick='cancel()' /></td></tr>";
infowindow = new google.maps.InfoWindow({
content: table
});
google.maps.event.addListener(map, "click", function(event) {
addMarker(event.latLng);
});
} //end initialize
// Add a marker to the map and push to the array, open an infowindow listener.
function addMarker(location) {
if (editon.editT[0].checked) edit = true; //check 'edit' radio buttons
if (editon.editT[1].checked) edit = false;
alert('infopen is ' + infopen);
if (edit== true && infopen== false) {
//if edit toggle is selected and infowindow not open
marker = new google.maps.Marker({
position: location, //from event.latLng
map: map,
draggable: true,
});
markers.push(marker); //add to markers array
google.maps.event.addListener(marker, "click", function() {
//listener for infowindow
infowindow.open(map, marker);
infopen = true; // stop the creation of new markers *in theory...
//alert('infopen is ' + infopen);
});
}// end if
} //end addMarker()
// Sets the map on all markers in the array. (only used when clearing)
function setAllMap(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
// Deletes all markers in the array by removing references to
them.
function deleteOverlays() {
setAllMap(null);
markers = [];
}
//would passes along info to php... not yet
function saveData() {
infowindow.close();
infopen = false; //reallow marker creation from click
}
//closes window and clears marker
function cancel() {
infowindow.close();
infopen = false; // reallow marker creation ***click still
heard by event listener***
marker.setMap(null); //just clears from map
}
</script>
</head>
<body onload="initialize()">
<br> </br>
<form name="editon"> Turn on editing:
<input type="radio" name="editT" value='true' checked/>Yes
<input type="radio" name="editT" value='false' />No
</form>
<div id="map_canvas" style="width:100%; height:70%"></div>
<p>If too cluttered:
<input onclick="deleteOverlays();" type=button value="Clear Map"/>
</body>
</html>

My contrived hack: add a setTimeout() around infowindow.close(). There is a rationale, explained below.
function saveData() {
setTimeout(function() { infowindow.close(); }, 100);
}
//closes window and clears marker
function cancel() {
setTimeout(function() { infowindow.close(); marker.setMap(null); }, 100);
}
100 ms seems reasonable. Strangely, setting the marker to a null map in cancel() also has to be timed out. I don't think you need infopen anymore.
I got the idea from this code sample:
http://code.google.com/apis/maps/articles/phpsqlinfo_v3.html
In this sample, the infoWindow is only closed (in a callback) after a database request is made and ensuring the response was good. Of course, this must take some milliseconds. So, under these assumptions, once you have your DB part working, you can replace the ugly setTimeout and everything should work! :)

Related

How to close POI's InfoWindow?

I'm trying to make POI's InfoWindow close when click a link.
I overrided the setContent of InfoWindow like this:
//override the built-in setContent-method
google.maps.InfoWindow.prototype.setContent = function (content) {
content = content.innerHTML + '<br/> Save place';
//run the original setContent-method
fx.apply(this, arguments);
};
Note: I didn't create any InfoWindow object to reference to use close() method.
In your override function capture a global reference to the infowindow so you can reference it to close it.
Your override of the infowindow doesn't work. I took a working version from this question: How to get a click event when a user clicks a (business) place on the map
proof of concept fiddle
code snippet:
var geocoder;
var map;
var infowindow;
//keep a reference to the original setPosition-function
var fx = google.maps.InfoWindow.prototype.setPosition;
// from https://stackoverflow.com/questions/24234106/how-to-get-a-click-event-when-a-user-clicks-a-business-place-on-the-map/24234818#24234818
//override the built-in setPosition-method
google.maps.InfoWindow.prototype.setPosition = function() {
//logAsInternal isn't documented, but as it seems
//it's only defined for InfoWindows opened on POI's
if (this.logAsInternal) {
// save reference in global infowindow variable.
infowindow = this;
google.maps.event.addListenerOnce(this, 'map_changed', function() {
var map = this.getMap();
//the infoWindow will be opened, usually after a click on a POI
if (map) {
//trigger the click
google.maps.event.trigger(map, 'click', {
latLng: this.getPosition()
});
}
});
}
//call the original setPosition-method
fx.apply(this, arguments);
};
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
google.maps.event.addDomListener(document.getElementById('btn'), 'click', function(e) {
// close the last opened POI infowindow
infowindow.close();
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="btn" type="button" value="close IW" />
<div id="map_canvas"></div>

Event listener to delete individual markers when they are clicked, only acts on last created marker

Hello and thanks in advance for your help!
The following test code:
1) Uses PHP to get lat/lng data from a mySQL database, and then uses that data to form a JavaScript array with initialization data. WORKS FINE.
2) Uses the initialized JavaScript array to create markers. WORKS FINE.
3) Allows (left) clicks to create new markers (more code will be added later to add those new marker locations back into the database). WORKS FINE.
4) Allows RIGHT-clicks to delete a marker using marker.setMap(null) - either the preloaded markers from the database, or newly created user markers. USER MARKERS DELETE PROPERLY, PRE-LOADED MARKERS DO NOT DELETE PROPERLY, AS DESCRIBED BELOW.
5) Both the preloaded markers, and the newly created ones are stored in the array "markers" using the statement markers.push(marker). SEEMS TO BE OK.
Everything works, except the right-click deletion of the PRELOADED markers. (The right-click deletion of user created markers works fine.) Any right-click on any preloaded marker, only deletes the LAST preloaded marker. It's as if the delete event listener were outside and after the loop that sets the preloaded markers, but it is inside that loop.
I think the faulty section is the one with the leading comment "show prev clicks in database". Any ideas would be greatly appreciated! I'm very new at Google Maps API v3, so it's probably something obvious that I'm just missing or misunderstanding. Thanks again!
<!DOCTYPE html>
<html>
<head>
<title>Marker Test</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas, #map_canvas {
height: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
<?
// Generate JavaScript array initialization from database
$username="REDACTED";
$password="REDACTED";
$database="REDACTED";
$con=mysql_connect(localhost,$username,$password);
#mysql_select_db($database,$con) or die( "Unable to select database");
$query="SELECT * FROM pool where (record_id >= 1765) AND (record_id <= 1769)";
/*
$query="SELECT * FROM pool where (record_id <= '$marker_end') AND (record_id >= '$marker_start')";
$query="SELECT * FROM pool where session = '$session'";
*/
$result=mysql_query($query,$con);
$length=mysql_num_rows($result);
$length_count=1;
if ($result) {
echo "var PreviousClicks = [\n";
while($row = mysql_fetch_array($result)) {
$_lat=$row['google_lat'];
$_lng=$row['google_lng'];
$_record_id=$row['record_id'];
echo "{\n";
echo "lat: $_lat,\n";
echo "lng: $_lng,\n";
echo "title: \"$_record_id\"\n";
echo "}";
if($length_count<$length) {echo ",\n";} else {echo "\n";}
$length_count++;
} // end while
echo "];";
} // end if
mysql_close();
?>
</script>
<script type="text/javascript">
var map;
var markers = [];
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
title: "A",
map: map
});
google.maps.event.addListener(marker, 'rightclick', function(event) {
marker.setMap(null);
});
markers.push(marker);
} //end addMarker function
function initialize() {
// currently manual center initialization
var startLoc = new google.maps.LatLng(33.037380,-117.090431);
var mapOptions = {
zoom: 16,
center: startLoc,
mapTypeId: google.maps.MapTypeId.TRAFFIC
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
});
// show prev clicks in database ------------------------------------------------------------------
for (i = 0; i < PreviousClicks.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(PreviousClicks[i].lat, PreviousClicks[i].lng),
title: PreviousClicks[i].title,
map: map
});
google.maps.event.addListener(marker, 'rightclick', function(event) {
marker.setMap(null);
});
markers.push(marker);
} // end for
// end "show prev clicks in database" section ----------------------------------------------------
} // end function initialize
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas">
</div>
</body>
</html>
Inside a marker's event handler, this refers back to the marker. Therefore :
this.setMap(null);
will remove the marker from the map.
But more can be done with this code. In particular :
Avoid repeating code by using addMarker() to add both new and previous markers.
When markers are removed, also remove them from the markers array.
Both can be achieved as follows :
function addMarker(event) {
var marker = new google.maps.Marker({
position: event.latLng,
title: event.title || "A",
map: map
});
google.maps.event.addListener(marker, 'rightclick', function(event) {
this.setMap(null);
//Remove the marker from the markers array.
for(i=0; i<markers.length; i++) {
if(markers[i] == this) {
removed = markers.splice(i, 1);
break;
}
}
});
markers.push(marker);
}
function initialize() {
...
google.maps.event.addListener(map, 'click', addMarker);
...
for (i = 0; i < PreviousClicks.length; i++) {
addMarker({
latLng: new google.maps.LatLng(PreviousClicks[i].lat, PreviousClicks[i].lng);
title: PreviousClicks[i].title
});
}
}

google maps loading map on button click - loading markers with another button

I'm trying to load markers on the click of a button, but somewhere i'm missing something. 1. map pulls out and loads with one button click. 2. markers load with the click of a different button. here's what i have:
<!DOCTYPE>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title></title>
<link rel="stylesheet" type="text/css" href="
<?php
$stylesarray = array("field");
echo $stylesarray[mt_rand(0,count($stylesarray)-1)];
?>.css">
<link rel="shortcut icon" href="images/favicon.ico">
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?key=xxx&sensor=false"></script>
<script type="text/javascript">
var map = null;
$(document).ready(function(){
var lat=document.getElementById("latitude");
var long=document.getElementById("longitude");
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition);
}
function showPosition(position) {
lat.value=+position.coords.latitude;
long.value=+position.coords.longitude;
}
});
function load() {
var map = new google.maps.Map(document.getElementById("mapcontainer"), {
center: new google.maps.LatLng(20,0),
zoom: 3,
styles: mapstyle,
mapTypeControl: false,
navigationControl: false,
streetViewControl: false,
maxZoom: 8,
minZoom: 3,
mapTypeId: 'roadmap'
});
}
function getmarkers(){
downloadUrl("markers.php", function(data) {
//alert ("it works");
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var id = markers[i].getAttribute("id");
var info = markers[i].getAttribute("info");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("latitude")),
parseFloat(markers[i].getAttribute("longitude")));
var date = markers[i].getAttribute("date");
var html = "<div id='tooltip'><div id='tiptext'>" + info
+ "<div id='number'>" + id + "</div>"
+ "<div id='date'>" + date + "</div>"
+ "</div></div>";
var marker = new google.maps.Marker({
map: map,
position: point,
icon: 'images/mapicon.png'
});
createTooltip(marker, html);
}
});
</script>
</head>
<body>
<div id="mapcontainer">
<form>
<input type="button" id="map" onClick="load()"></input>
</form>
<form>
<input type="button" onClick="getmarkers()"></input>
</form>
</body>
</html>
xml sample:
<markers>
<marker id="330" info="blahblah" date="2012-10-03" latitude="20.00" longitude="-81.00"/>
</markers>
Your map variable is local to your initialize function. It won't be accessible to the code that loads the markers.
Try defining it globally (outside of any functions):
var map = null;
Then initialize it in your load function
function load() {
map = new google.maps.Map(document.getElementById("mapcontainer"), {
The problem (after syntax errors) with your posted code is that the getmarkers function is local to the load function. It needs to be global to be called by an HTML element click function.
Live working version based off your example code
It seems like you do not declare the map variable in the global scope. Only in the load function scope, declare it as a global variable and it should work.
var map = null; // Declaring map in the global scope
function load() {
// map references to global scope
map = new google.maps.Map(document.getElementById("mapcontainer"), {
...
}
downloadUrl("markerinfo.php", function(data) {
...
var marker = new google.maps.Marker({
map: map, // map references to global scope
position: point,
icon: 'images/mapicon.png'
});
createTooltip(marker, html);
}
});
Try wrapping the DownloadUrl function call in another function and call that instead.
<input type="button" id="markerload" onClick="getMarkers()"></input>
function getMarkers() {
downloadUrl("markerinfo.php", function(data) {
...
});
}
function getmarkers() is designed to retrieve all markers with a for loop
for (var i = 0; i < markers.length; i++) {
To load one marker at a time you will need to increment it for each button click
Ie Var i =0 globally
Increment i at end of getmarkers() i++
You should stop the increments after the last member of array when it gets to markers.length

How to display content in an infowindow specific to a marker?

I created a google maps (api v3) with the number of markers depending on the search results. When I click a marker, it opens an infowindow. What's the best way to have that infowindow show information associated to its marker? The information related to all the markers is in a json object I receive from an ajax request.
for (i=0; i < result.point.length; i++) {
var latLng = new google.maps.LatLng(result.proint[i].Latitude,result.point[i].Longitude);
var marker = new google.maps.Marker({
position: latLng,
title: i.toString()
//map: map
});
markersArray.push(marker);
var infowindow = new google.maps.InfoWindow({
content: 'specific information associated to the marker clicked'
});
google.maps.event.addListener(markersArray[i], 'click', function(event) {
infowindow.open(map, this);
});
Create only 1 infoWindow as suggested above.
The content store inside the marker:
var marker = new google.maps.Marker({
position: latLng,
title: i.toString(),
//set your content here
content:'your specific content'
//map: map
});
The opening of the window:
google.maps.event.addListener(markersArray[i], 'click', function(event) {
infoWindow.setContent(this.content);
infowindow.open(map, this);
});
First, you should move the the creation of the infoWindow out of the for loop.
Next, change where you attach the click event to this:
google.maps.event.addListener(markersArray[i], 'click', function(content) {
return function(event){
infowindow.setContent(content);
infowindow.open(map, this);
}
}(WHATEVER_THE_CONTENT_SHOULD_BE_FOR_THIS_MARKER));
You want to use this instead of marker. this will refer to the object the event took place on, while marker will refer to the last marker created.
You have some typos in your example (proint) At the top of you loop:
for (i=0; i < result.point.length; i++) {
var info_window_content = result.point[i].Latitude + '<br />';
info_window_content += result.point[i].Longitue + '<br />';
// etc for any value in you json object
// create your marker as is.
...
var infowindow = new google.maps.InfoWindow({
content: info_window_content
});
// etc, etc.
You do need to add an eventListener to each marker, as you are doing. I don't see any problem with that.
Except I'd use infoWindow.open(map, marker) vs. this.
There is probably a more efficient way to do it, i.e. after infoWindow.open(); infoWindow.setContent(info_window_content)
Try this, it works I tested it already
// Add markers
for (i=0; i < result.point.length; i++) {
var latLng = new google.maps.LatLng(result.proint[i].Latitude, result.point[i].Longitude);
var marker = new google.maps.Marker({
position: latLng,
title: i.toString()
//map: map
});
// marker info start
var infowindow = new google.maps.InfoWindow();
(function (marker, result.point[i]) {
// add click event
google.maps.event.addListener(marker, 'click', function() {
var infoContent: "specific information associated to the marker clicked"
});
infoWindow.setContent(infoContent);
infowindow.open(map, marker);
});
// selected marker 4 infowindow
(marker, result.point[i]);
markersArray.push(marker);
}
Not entirely sure what it is you are trying to do. Where/ what content are you trying to load?
google.maps.event.addListener(marker, 'click', (function(event, index) {
return function(){
infowindow.content = markersArray[index].yourcontent;
// or
infowindow.content = yourcontentarray[index];
infowindow.open(map,this);
}
})(marker,i));
Make sure you declare your marker and infowindow variables outside of a function.

Retrieve latitude and longitude of a draggable pin via Google Maps API V3

I will explain. I managed to have a draggable pin on a map. I want to retrieve the coordinates of this point and put them into two fields: Latitude and Longitude. These coordinates will later be send to a SQL table via PHP.
Here is an example of what I intend to do, but instead of several pins, it's just one and it's draggable. The problem is: I'm not even able to display the coordinates of the initial point. And of course when the user moves the pin, I want the coordinates to change as well in the fields.
I hope I made myself clear. What did I do wrong? Should I use the Geocoding service?
Here goes the JS:
<script type="text/javascript">
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(40.713956,-74.006653);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
draggable: true,
position: myLatlng,
map: map,
title: "Your location"
});
google.maps.event.addListener(marker,'click',function(overlay,point){
document.getElementById("latbox").value = lat();
document.getElementById("lngbox").value = lng();
});
}
</script>
And the HTML:
<html>
<body onload="initialize()">
<div id="map_canvas" style="width:50%; height:50%"></div>
<div id="latlong">
<p>Latitude: <input size="20" type="text" id="latbox" name="lat" ></p>
<p>Longitude: <input size="20" type="text" id="lngbox" name="lng" ></p>
</div>
</body>
</html>
Either of these work
google.maps.event.addListener(marker, 'click', function (event) {
document.getElementById("latbox").value = event.latLng.lat();
document.getElementById("lngbox").value = event.latLng.lng();
});
google.maps.event.addListener(marker, 'click', function (event) {
document.getElementById("latbox").value = this.getPosition().lat();
document.getElementById("lngbox").value = this.getPosition().lng();
});
You might also consider using the dragend event also
google.maps.event.addListener(marker, 'dragend', function (event) {
document.getElementById("latbox").value = this.getPosition().lat();
document.getElementById("lngbox").value = this.getPosition().lng();
});
Look at the official code sample from Google Maps API reference:
http://gmaps-samples-v3.googlecode.com/svn/trunk/draggable-markers/draggable-markers.html
The code that is actually working is the following:
google.maps.event.addListener(marker, 'drag', function(event){
document.getElementById("latbox").value = event.latLng.lat();
document.getElementById("lngbox").value = event.latLng.lng();
});
It would be better if the map could be re-centered once the pin is dropped. I guess it can be done with map.setCenter() but I'm not sure where I should put it. I tried to put it right before and right after this piece of code but it won't work.
Google Maps V3 Example. Here's a working example of a user dropping a single pin, replacing a dropped pin with new pin, custom pin images, pins that populate lat/long values in a FORM FIELD within a DIV.
<html>
<body onLoad="initialize()">
<div id="map_canvas" style="width:50%; height:50%"></div>
<div id="latlong">
<p>Latitude: <input size="20" type="text" id="latbox" name="lat" ></p>
<p>Longitude: <input size="20" type="text" id="lngbox" name="lng" ></p>
</div>
</body>
</html>
<cfoutput>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=#YOUR-GOOGLE-API-KEY#&sensor=false"></script>
</cfoutput>
<script type="text/javascript">
//<![CDATA[
// global "map" variable
var map = null;
var marker = null;
// popup window for pin, if in use
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150,50)
});
// A function to create the marker and set up the event window function
function createMarker(latlng, name, html) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
google.maps.event.trigger(marker, 'click');
return marker;
}
function initialize() {
// the location of the initial pin
var myLatlng = new google.maps.LatLng(33.926315,-118.312805);
// create the map
var myOptions = {
zoom: 19,
center: myLatlng,
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// establish the initial marker/pin
var image = '/images/googlepins/pin2.png';
marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image,
title:"Property Location"
});
// establish the initial div form fields
formlat = document.getElementById("latbox").value = myLatlng.lat();
formlng = document.getElementById("lngbox").value = myLatlng.lng();
// close popup window
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// removing old markers/pins
google.maps.event.addListener(map, 'click', function(event) {
//call function to create marker
if (marker) {
marker.setMap(null);
marker = null;
}
// Information for popup window if you so chose to have one
/*
marker = createMarker(event.latLng, "name", "<b>Location</b><br>"+event.latLng);
*/
var image = '/images/googlepins/pin2.png';
var myLatLng = event.latLng ;
/*
var marker = new google.maps.Marker({
by removing the 'var' subsquent pin placement removes the old pin icon
*/
marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
title:"Property Location"
});
// populate the form fields with lat & lng
formlat = document.getElementById("latbox").value = event.latLng.lat();
formlng = document.getElementById("lngbox").value = event.latLng.lng();
});
}
//]]>
</script>
Check this fiddle
In the following code replace dragend with the event you want. In your case 'click'
google.maps.event.addListener(marker, 'dragend', function (event) {
document.getElementById("defaultLatitude").value = event.latLng.lat();
document.getElementById("defaultLongitude").value = event.latLng.lng();
});
google.maps.event.addListener(marker, 'dragend', function (event) {
document.getElementById("latbox").value = this.getPosition().lat();
document.getElementById("lngbox").value = this.getPosition().lng();
});
worked well for me.. Thanks..
var zoomLevel = map.getZoom();
var pos = (event.latLng).toString();
$('#position').val(zoomLevel+','+pos); //set value to some input
Example Run JsFiddle
tRy This :)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!--
develop by manoj sarnaik
-->
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Manoj Sarnaik</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAjU0EJWnWPMv7oQ-jjS7dYxSPW5CJgpdgO_s4yyMovOaVh_KvvhSfpvagV18eOyDWu7VytS6Bi1CWxw"
type="text/javascript"></script>
<script type="text/javascript">
var map = null;
var geocoder = null;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(20.236046, 76.988255), 1);
map.setUIToDefault();
geocoder = new GClientGeocoder();
}
}
function showAddress(address) {
if (geocoder) {
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert(address + " not found");
} else {
map.setCenter(point, 15);
var marker = new GMarker(point, {draggable: true});
map.addOverlay(marker);
GEvent.addListener(marker, "dragend", function() {
marker.openInfoWindowHtml(marker.getLatLng().toUrlValue(6));
});
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(marker.getLatLng().toUrlValue(6));
});
GEvent.trigger(marker, "click");
}
}
);
}
}
</script>
</head>
<body onload="initialize()" onunload="GUnload()">
<form action="#" onsubmit="showAddress(this.address.value); return false">
<p>
<input type="text" style="width:350px" name="address" value="Malegaon,washim" />
<input type="submit" value="Go!" />
</p>
<div id="map_canvas" style="width: 600px; height: 400px"></div>
</form>
</body>
</html>

Resources