Switching between layers in Google Fusion Map using drop down box - google-maps-api-3

Having successfully followed some Fusion Map examples, with a little help from people here. I'm trying to do something I've been able to find an example of...
My map contains 3 layers, but I only want to show 2 at a time. I've therefore added a drop down box at the bottom so that you can switch between 2 of the maps. I've added a variable "SecondLayerMap", and I think (i've at least tried) to get the drop down box to change this variable. I'd never written any Java (or any other programming language) until 3 weeks ago, so it's been a steep learning curve!
[One method I've seen some people use in a similar situation has been to use 1 fusion table, but switch between data in different columns. I don't think I can do this because the geodata in each table is different and I don't want them both displayed at the same time.]
The next step will be to change one of the legends with the switch in map, but I'll take what i learn from this problem, before tackling that one...
Thanks for your help.
<meta charset="UTF-8">
<title>Smithfield Foods UK</title>
<link rel="stylesheet" type="text/css" media="all" href="FusionMapTemplate.css" />
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() {
var defaultZoom = 10;
var defaultCenter = new google.maps.LatLng(52.6500, 1.2800);
var locationColumn = 'geometry';
var geocoder = new google.maps.Geocoder();
var SecondLayerMap = '1RrCcRC-1vU0bfHQJTQWqToR-vllSsz9iKnI5WEk'
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: defaultCenter,
zoom: defaultZoom,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infoWindow = new google.maps.InfoWindow();
// Initialize the first layer
var FirstLayer = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: '1hpGzmMBg8bDgPOGrAXvc0_QVLSBqQ0O5vpLbfUE'
},
map: map,
styleId: 3,
templateId: 5,
suppressInfoWindows: true
});
google.maps.event.addListener(FirstLayer, 'click', function(e) {windowControl(e, infoWindow, map);
});
// Initialize the second layer
var SecondLayer = new google.maps.FusionTablesLayer({
query: {
select: 'PostCode',
from: SecondLayerMap
},
map: map,
styleId: 2,
templateId: 2,
suppressInfoWindows: true
});
google.maps.event.addDomListener(document.getElementById('store'), 'change', function() {
var SecondLayerMap = this.value;
SecondLayer = new google.maps.FusionTablesLayer({
query: {
select: 'Postcode',
from: SecondLayerMap
}
});
});
google.maps.event.addListener(SecondLayer, 'click', function(e) {windowControl(e, infoWindow, map);
});
var legend = document.createElement('div');
legend.id = 'legend';
var content = [];
content.push('<h3>Density of Polish speaking population</h3>');
content.push('<p><div class="color red1"></div>=>2%<4%');
content.push('<p><div class="color red2"></div>=>4%<6%');
content.push('<p><div class="color red3"></div>=>6%<10%');
content.push('<p><div class="color red4"></div>=>10%<15%');
content.push('<p><div class="color red5"></div>=>15%<20%')
content.push('<p><img src="Smithfield Black.png" alt="Smithfield Logo" width ="120px">');
legend.innerHTML = content.join('');
legend.index = 1;
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(legend);
var legend2 = document.createElement('div');
legend2.id = 'legend2';
var content2 = [];
content2.push("<h3>Smithfield Food's sales in Asda Stores</h3>");
content2.push('<p><img src="red-dot.png"><£1,000');
content2.push('<p><img src="yellow-dot.png">=>£1,000<£20,000');
content2.push('<p><img src="green-dot.png">=>£20,000<£40,000');
legend2.innerHTML = content2.join('');
legend2.index = 1;
map.controls[google.maps.ControlPosition.RIGHT_TOP].push(legend2);
var zoomToAddress = function() {
var address = document.getElementById('address').value;
geocoder.geocode({
address: address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
map.setZoom(10);
} else {
window.alert('Address could not be geocoded: ' + status);
}
});
};
google.maps.event.addDomListener(document.getElementById('search'), 'click', zoomToAddress);
google.maps.event.addDomListener(window, 'keypress', function(e) {
if (e.keyCode ==13) {
zoomToAddress();
}
});
google.maps.event.addDomListener(document.getElementById('reset'), 'click', function() {
map.setCenter(defaultCenter);
map.setZoom(defaultZoom);
layer.setOptions({
query: {
select: 'geometry',
from: '1hpGzmMBg8bDgPOGrAXvc0_QVLSBqQ0O5vpLbfUE'
}
});
});
}
// Open the info window at the clicked location
function windowControl(e, infoWindow, map) {
infoWindow.setOptions({
content: e.infoWindowHtml,
position: e.latLng,
pixelOffset: e.pixelOffset
});
infoWindow.open(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<div>
<label>Enter an address:</label>
<input type="text" id="address" value="Leeds">
<input type="button" id="search" value="Search">
<input type="button" id="reset" value="Reset">
</div>
<div>
<select id="store">
<option value ="1RrCcRC-1vU0bfHQJTQWqToR-vllSsz9iKnI5WEk">Store A</option>
<option value ="1QX6QXhAiHXXAcS96RSAmE1Caj8tWebc6d-1_Tjk">Store B</option>
</select>
</body>

Use setOptions() to apply the query to the layer:
google.maps.event.addDomListener(document.getElementById('store'),
'change',
function() {
var SecondLayerMap = this.value;
SecondLayer.setOptions({
query: {
select: 'Postcode',
from: SecondLayerMap
}
});

Related

Search address on Google Map v3 by pressing ENTER

I have working java script Google Map Api v3 with Geocoding.
When I type for example post code in search box I can select address from list. If I will do same thing and press ENTER nothing is happening. How to modify code?
<input id="address" type="textbox">
Java script code:
var geocoder;
var map;
var marker;
function initialize(){
//MAP
var latlng = new google.maps.LatLng(51.469186, -0.361166);
var options = {
zoom: 11,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), options);
//GEOCODER
geocoder = new google.maps.Geocoder();
marker = new google.maps.Marker({
map: map,
draggable: false
});
//CIRCLE
var circle = new google.maps.Circle({
map: map,
center: new google.maps.LatLng(51.469186, -0.361166),
fillColor: '#204617',
fillOpacity: 0.2,
strokeColor: '#6DE953',
strokeOpacity: 0.4,
strokeWeight: 2
});
circle.setRadius(10000);
}
$(document).ready(function() {
initialize();
$(function() {
$("#address").autocomplete({
//This bit uses the geocoder to fetch address values
source: function(request, response) {
geocoder.geocode( {'address': request.term }, function(results, status) {
response($.map(results, function(item) {
return {
label: item.formatted_address,
value: item.formatted_address,
latitude: item.geometry.location.lat(),
longitude: item.geometry.location.lng()
}
}));
})
},
//This bit is executed upon selection of an address
select: function(event, ui) {
var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
marker.setPosition(location);
map.setCenter(location);
}
});
document.getElementById("address").focus();
});
});
I have try adding search button:
<input id="search" type="button" value="Search" onclick="codeAddress()">
and adding function codeAddress() to Java Script but I must have done something wrong as that didn't worked.
Working (without ENTER) jsfiddle
you can try this maybe you'll get some ideas. https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform
they are also using geocode, so you can refer the code.
I'm not a 100% certain what you are doing wrong, since you did not post all the code. But this example works (I tested in FF):
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script> <!-- Google Maps API -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
var geocoder;
var map;
var marker;
function initialize(){
//MAP
var latlng = new google.maps.LatLng(51.469186, -0.361166);
var options = {
zoom: 11,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), options);
//GEOCODER
geocoder = new google.maps.Geocoder();
marker = new google.maps.Marker({
map: map,
draggable: false
});
//CIRCLE
var circle = new google.maps.Circle({
map: map,
center: new google.maps.LatLng(51.469186, -0.361166),
fillColor: '#204617',
fillOpacity: 0.2,
strokeColor: '#6DE953',
strokeOpacity: 0.4,
strokeWeight: 2
});
circle.setRadius(10000);
}
</script>
<script>
$(document).ready(function() {
initialize();
$(function() {
$("#address").autocomplete({
//This bit uses the geocoder to fetch address values
source: function(request, response) {
geocoder.geocode( {'address': request.term }, function(results, status) {
response($.map(results, function(item) {
return {
label: item.formatted_address,
value: item.formatted_address,
latitude: item.geometry.location.lat(),
longitude: item.geometry.location.lng()
}
}));
})
},
//This bit is executed upon selection of an address
select: function(event, ui) {
var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
marker.setPosition(location);
map.setCenter(location);
}
});
document.getElementById("address").focus();
});
});
</script>
<style>
/* style settings for Google map */
#map_canvas
{
width : 500px; /* map width */
height: 500px; /* map height */
}
</style>
</head>
<body onload="initialize()">
<!-- Dislay Google map here -->
<div id='map_canvas' ></div>
<input id="address" type="textbox">
</body>
</html>

Implementing MarkerClusterer into Google Maps API - no markers showing

I have been trying to implement markerclusterer into my website for the past few weeks and everything I have tried has failed. I have no experience with code at all so everything I've been doing is trial and error.
The website I'm trying to add markerclusterer to is rfmaps.com.au.
I'm unsure as to what I'm doing wrong, and what needs to be fixed and really just need some good advice and help.
Here is the html code that I've been trying to get working. This code is simply all the bits and pieces I've been able to find from forums, all stuck together, and slightly edited (what I could figure out from help from forums)
<!DOCTYPE html>
<html>
<head>
<style>
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var map;
var layerl0;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(-25, 133),
zoom: 5,
mapTypeId: google.maps.MapTypeId.HYBRID
});
for (var i = 0; i < 1000; ++i) {
var latLng = new google.maps.LatLng(data.photos[i].latitude,
data.photos[i].longitude)
var marker = new google.maps.Marker({
position: latLng,
draggable: true,
icon: markerImage
});
markers.push(marker);
}
var map = new google.maps.Map(document.getElementById("map"), options);
var mc = new MarkerClusterer(map);
layerl0 = new google.maps.FusionTablesLayer({
query: {
select: "'col2'",
from: '1UxncvVQSGcSvuN3t686sNuDQUsn8vQ6mws3zsvk'
},
map: map,
styleId: 4,
templateId: 1
});
}
function changeMapl0() {
var searchString = document.getElementById('search-string-l0').value.replace(/'/g, "\\'");
layerl0.setOptions({
query: {
select: "'col2'",
from: '1UxncvVQSGcSvuN3t686sNuDQUsn8vQ6mws3zsvk',
where: "'Location' CONTAINS IGNORING CASE '" + searchString + "'"
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<div style="margin-top: 10px;">
<label>Location</label><input type="text" id="search-string-l0">
<input type="button" onClick="changeMapl0()" value="Search">
</div>
</body>
</html>
I think you have not added the 'map' object while creating the markers inside the map.
This is your code:
var marker = new google.maps.Marker({
position: latLng,
draggable: true,
icon: markerImage
});
Please add map: map while generating your markers, like this:
var marker = new google.maps.Marker({
map: map,
position: latLng,
draggable: true,
icon: markerImage
});
Regarding marker cluster you need to add this js file- markerclusterer.js
markerCluster = new MarkerClusterer(map, marker);

zoomToAddress not working on Google Fusion Map

I've followed the search and zoom example from here: https://developers.google.com/fusiontables/docs/samples/search_and_zoom
and I've managed to get the "Reset" button to work, but the "Search" button isn't working. I wondered if it was because I am using 2 layers, but I don't know how to correct by java script if that is that case. Any help appreciated. Thanks.
<html>
<head>
<meta charset="UTF-8">
<title>Smithfield Foods UK</title>
<link rel="stylesheet" type="text/css" media="all" href="FusionMapTemplate.css" />
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() {
var defaultZoom = 10;
var defaultCenter = new google.maps.LatLng(52.6500, 1.2800)
var locationColumn = 'geometry'
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: defaultCenter,
zoom: defaultZoom,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infoWindow = new google.maps.InfoWindow();
// Initialize the first layer
var FirstLayer = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: '1hpGzmMBg8bDgPOGrAXvc0_QVLSBqQ0O5vpLbfUE'
},
map: map,
styleId: 3,
templateId: 5,
suppressInfoWindows: true
});
google.maps.event.addListener(FirstLayer, 'click', function(e) {windowControl(e, infoWindow, map);
});
// Initialize the second layer
var SecondLayer = new google.maps.FusionTablesLayer({
query: {
select: 'PostCode',
from: '1RrCcRC-1vU0bfHQJTQWqToR-vllSsz9iKnI5WEk'
},
map: map,
styleId: 2,
templateId: 2,
suppressInfoWindows: true
});
google.maps.event.addListener(SecondLayer, 'click', function(e) {windowControl(e, infoWindow, map);
});
var legend = document.createElement('div');
legend.id = 'legend';
var content = [];
content.push('<h3>Density of Polish speaking population</h3>');
content.push('<p><div class="color red1"></div>=>2%<4%');
content.push('<p><div class="color red2"></div>=>4%<6%');
content.push('<p><div class="color red3"></div>=>6%<10%');
content.push('<p><div class="color red4"></div>=>10%<15%');
content.push('<p><div class="color red5"></div>=>15%<20%')
content.push('<p><img src="Smithfield Black.png" alt="Smithfield Logo" width ="120px">');
legend.innerHTML = content.join('');
legend.index = 1;
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(legend);
var legend2 = document.createElement('div');
legend2.id = 'legend2';
var content2 = [];
content2.push("<h3>Smithfield Food's sales in Asda Stores</h3>");
content2.push('<p><img src="red-dot.png"><£1,000');
content2.push('<p><img src="yellow-dot.png">=>£1,000<£20,000');
content2.push('<p><img src="green-dot.png">=>£20,000<£40,000');
legend2.innerHTML = content2.join('');
legend2.index = 1;
map.controls[google.maps.ControlPosition.RIGHT_TOP].push(legend2);
var zoomToAddress = function() {
var address = document.getElementById('address').value;
geocoder.geocode({
address: address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
map.setZoom(10);
} else {
window.alert('Address could not be geocoded: ' + status);
}
});
};
google.maps.event.addDomListener(document.getElementById('search'), 'click', zoomToAddress);
google.maps.event.addDomListener(window, 'keypress', function(e) {
if (e.keyCode ==13) {
zoomToAddress();
}
});
google.maps.event.addDomListener(document.getElementById('reset'), 'click', function() {
map.setCenter(defaultCenter);
map.setZoom(defaultZoom);
layer.setOptions({
query: {
select: 'geometry',
from: '1hpGzmMBg8bDgPOGrAXvc0_QVLSBqQ0O5vpLbfUE'
}
});
});
}
// Open the info window at the clicked location
function windowControl(e, infoWindow, map) {
infoWindow.setOptions({
content: e.infoWindowHtml,
position: e.latLng,
pixelOffset: e.pixelOffset
});
infoWindow.open(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<div>
<label>Enter an address:</label>
<input type="text" id="address" value="Leeds">
<input type="button" id="search" value="Search">
<input type="button" id="reset" value="Reset">
</div>
</body>
</html>
I get a "geocoder is undefined" error". Because it isn't defined.
One way to fix it would be to add this to the global scope (just before your initialize function):
var geocoder = new google.maps.Geocoder();
Or you could do it the way it is done in the example you used, it is inside the initialize function there.
working example

markerclusterer limits

Hi this is my first post here..
I have been playing around with google maps trying to make a list of campsites in France.
I have got to the point of reading an xml file of the data
Loading the map and clustering the results and it all works but very slow.
Q1 Is there a limit on the number of markers you can render even using the clusterer (there are >7000 records at the moment)
Q2
Is there anything obviously wrong with the code I have so far:
<!DOCTYPE html>
<html>
<head>
<title>Read XML in Microsoft Browsers</title>
<script src="http://maps.google.com/maps/api/js?sensor=false&language=en&region=GB" type="text/javascript"></script>
<script src="scripts/markerclusterer.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="stylesheets/style_1024.css" />
<script type="text/javascript">
var xmlDoc;
function loadxml() {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.onreadystatechange = readXML;
xmlDoc.load("xml_files/France_all.xml");
}
function readXML() {
if (xmlDoc.readyState == 4) {
//alert("Loaded");
//set up map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(0, 0),
mapTypeControl: true,
mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow({ maxWidth: 100 });
var marker, i
var markers = [];
var html = [];
var x = (xmlDoc.getElementsByTagName("placemark").length);
//for (i = 0; i < x; i++) {
for (i = 0; i < x; i++) {
//document.write(xmlDoc.documentElement.childNodes[1].firstChild.tagName) + '<br>';
desc = xmlDoc.getElementsByTagName("description")[i].text;
lat = parseFloat((xmlDoc.getElementsByTagName("latitude")[i].text));
lon = parseFloat((xmlDoc.getElementsByTagName("longitude")[i].text));
myicon = (xmlDoc.getElementsByTagName("icon")[i].text);
//create new point
var point = new google.maps.LatLng(lat, lon);
//create new marker
marker = new google.maps.Marker({
position: point,
panControl: false,
map: map,
icon: myicon
});
//increae map bounds
bounds.extend(point);
//fit to bounds
map.fitBounds(bounds);
//add reference to arrays
markers.push(marker);
html.push(desc);
//add listener
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(html[i]);
infowindow.open(map, marker);
}
})(marker, i));
//alert(i + " " + desc +" added!");
};
//var mc = new MarkerClusterer(map);
var mcOptions = {gridSize: 50, maxZoom: 15 };
var mc = new MarkerClusterer(map, markers, mcOptions);
}
}
</script>
</head>
<body onload="loadxml()">
<div style="height:100%; width:100%">
<div id="map" style="float:left; width:50%; height:100%">
<!--filled via script-->
</div>
<div style="float:left; width:50%; height:100%">
<h4>Select Region</h4>
<select>
<option value="Alsace" onclick="loadxml()">Alsace</option>
</select>
</div>
</div>
</body>
</html>
This article may help. A tile based solution (FusionTables, KmlLayer, or a server based custom map) will render more quickly than native Google Maps API v3 objects, even with clustering. You may be seeing the transfer and processing time of the xml file.

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