zoomToAddress not working on Google Fusion Map - google-maps-api-3

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

Related

Google Maps API Uncaught TypeError: Cannot read property '__e3ae_' of undefinedT.trigger

<!DOCTYPE html >
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>langganan</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="markercluster.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
var cluster = [];
function load(lt,lg,zoom) {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(lt, lg),
zoom: zoom,
mapTypeId: 'roadmap'
});
var infowindow = new google.maps.InfoWindow();
downloadUrl("phpsqlajax_genxml3.php ", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("nama");
var address = markers[i].getAttribute("alamat");
var type = markers[i].getAttribute("wilayah");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
cluster.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
map.setZoom(17);
map.setCenter(marker.getPosition());
infowindow.setContent("Kode Pelanggan : "+markers[i].getAttribute("kode_pelanggan")+"<br/>"+
"Nama Pelanggan : "+markers[i].getAttribute("nama")+"<br/>"+
"Alamat Pelanggan : "+markers[i].getAttribute("alamat")+"<br/>"+
"Wilayah : "+markers[i].getAttribute("wilayah"));
infowindow.open(map, marker);
}
})(marker, i));
}
var a=15;
var mc = new MarkerClusterer(map, cluster,{
maxZoom: a /*,
// gridSize: size,
// styles: styles[style]
// */
}
);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
// google.maps.event.trigger(marker,'click');
function info(x)
{
google.maps.event.trigger(cluster[x],'click');
}
function replaceAll(find, replace, str) {
return str.replace(new RegExp(find, 'g'), replace);
}
function get(){
var tempout;
$.post('tampil.php',{ ambil: frm.ambil.value},
function(output){
var tampung = output.replace("[", "");
tampung = tampung.replace("]", "");
tampung = replaceAll('"',"",tampung);
var kode = tampung.split(",");
var latx = kode[3];
var lngx = kode[4];
load(latx,lngx,17);
info(kode[0]);
$('#nama').html(output).show();
}
);
}
function doNothing() {}
//]]>
</script>
<script type="text/javascript">
</script>
</head>
<body onload=load(-5.162764,119.443118,13)>
<form name="frm">
<center><input type="text" id="ambil" name="ambil" value="">
<input type="button" id="Cari"value="Cari" onClick="get(); "/></br>
<div id="nama"></div></center>
Open Info Window
</form>
<div id="map" style="width: 600px; height: 400px" ></div></hr>
</body>
</html>
I'm currently use a new system for my gis website and I'm getting the following error: Uncaught TypeError: Cannot read property '__e3ae_' of undefinedT.trigger
# main.js:18info # map.php:112(anonymous function)
# map.php:134jQuery.Callbacks.fire # jquery.js:3143jQuery.Callbacks.self.fireWith # jquery.js:3255done # jquery.js:9309jQuery.ajaxTransport.send.callback # jquery.js:9713

i get undefined at marker properties

i user markerclustererplus and i want to show info window on cluster click. but i get undefined for all marker in a cluster. i just can't figure it out why and what can be happened. here is my code
<!DOCTYPE html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>PHP/MySQL & Google Maps Example</title>
<style type="text/css">
html, body, #map { margin: 0; padding: 0; height: 95% }
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn-history/r315/trunk/markerwithlabel/src/markerwithlabel_packed.js"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer.js" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var oncekimarker=null;
var customIcons = {
satilik: {
icon: 'images/pins/yellow.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
kiralik: {
icon: 'images/pins/blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function initialize() {
var markers = null;
var mcmarkers = [];
var globalMarker = [];
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(39, 35),
zoom: 6,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
var infowindow = new google.maps.InfoWindow();
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = data.responseXML;
markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"))
var point = new google.maps.LatLng(lat, lng);
var html = "something";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
mcmarkers.push(marker);
bindInfoWindow(marker, map, infoWindow, html);
}
var mcOptions = {
gridSize: 30,
maxZoom: 13,
zoomOnClick: false,
averageCenter: true
};
var mc = new MarkerClusterer(map, mcmarkers, mcOptions);
google.maps.event.addListener(mc, 'clusterclick', function(cluster) {
var content = '';
// Convert lat/long from cluster object to a usable MVCObject
var info = new google.maps.MVCObject;
info.set('position', cluster.center_);
//Get markers
var yazmarkers = cluster.getMarkers();
var titles = "";
//Get all the titles
for(var i = 0; i < yazmarkers.length; i++) {
titles += yazmarkers[i].name + "\n";
}
infowindow.close();
infowindow.setContent(titles); //set infowindow content to titles
infowindow.open(map, info);
google.maps.event.addListener(map, 'zoom_changed', function() { infowindow.close() });
});
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
//infoWindow.open(map, marker);
if (oncekimarker) oncekimarker.setAnimation(null);
marker.setAnimation(google.maps.Animation.BOUNCE);
oncekimarker = marker;
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
</div>
<div id="map" style="width: 80%"></div>
</body>
</html>
any help whoul be appreciated. thanks for all your helps.
Your markers do not have a "name" property.
titles += yazmarkers[i].name + "\n";
You can add one by creating them like this
var marker = new google.maps.Marker({
name: name,
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
Warning: While this works with the API at present, it is not documented behavior, you may want to use the "title" property instead, which is documented and has the benefit of appearing on the Marker as a tooltip on mouseover.
working example

Switching between layers in Google Fusion Map using drop down box

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
}
});

How could i show info window for ten markers in google maps?

dear professionals.
I want to make info window for each markers on google maps.
My code:
google.maps.event.addListener(marker, 'click', function() {
new google.maps.InfoWindow({content: content}).open(map, marker);
});
show infowindow only for last marker.
Please, give me example or link to tutorial.
This is a modification of my answer to this question: Maps API Javascript v3 how to load markers with a mouse click
It loads an array of markers with info windows, and displays the last one added.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>boats</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js' type='text/javascript'></script>
<script type="text/javascript">
</script>
</head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var infowindow = null;
var map = null;
function initialize() {
var washington = new google.maps.LatLng(47.7435, -122.1750);
var myOptions = {
zoom: 7,
center: washington,
mapTypeId: google.maps.MapTypeId.TERRAIN
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
infowindow = new google.maps.InfoWindow({ content: "loading..." });
boats(map, seller);
}
var seller = [
['joe boat', 48.0350,-122.2570, 4, 'This is in good shape.'],
['bobs boat', 48.7435, -122.1750, 2, 'This is in bad shape.'],
['bubas boat', 47.3435, -122.1750, 1, 'This is in ok shape'],
['daveys boat', 47.7435, -122.1750, 3, 'dont buy this one.']
];
function boats(map, markers) {
for (var i = 0; i < markers.length; i++) {
var seller = markers[i];
var sellerLatLng = new google.maps.LatLng(seller[1], seller[2]);
var marker = new google.maps.Marker({
position: sellerLatLng,
map: map,
title: seller[0],
zIndex: seller[3],
html: seller[4]
});
var contentString = "content";
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
}
// display the last marker infowindow
infowindow.setContent(marker.html);
infowindow.open(map,marker);
}
</script>
<body onLoad="initialize()">
<div id="map_canvas" style="width: 450px; height: 350px;">map div</div>
</body>
</html>

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