I am having trouble fitting auto center and auto Zoom on a map created from a CSV file that goes into a PHP array then transferred into JavaScript--code as follows -
<!DOCTYPE html>
<?php
include "getCsvData.php"; // this is where we put the data into a PHP array called $dataArray;
// now we exit the PHP and do the HTML including our Javascript...
?>
<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>Google Maps JavaScript API v3 Example: Geocoding Simple</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/standard.css" rel="stylesheet"
type="text/css"/>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
var markers = [];
var image = {
url: 'src/icon' + 'a.png'
,
};
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(0, 0);
var myOptions = {
zoom: 7,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
<?php
for($i = 0, $j = count($postcodes); $i < $j - 1 ; $i++) {
?>
addPostCode(<?php echo str_replace(array('[', ']'), '', json_encode($postcodes[$i])); ?>);
<?php } ?>
}
function addPostCode(zip) {
geocoder.geocode({'address': zip}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
icon: image,
position: results[0].geometry.location,
name: zip
});
markers.push(marker);
// latlng.extend(marker.position);
} else if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(function () {
Geocode(address);
}, 200);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="height:90%"></div>
</body>
</html>
I have found I need to use fitBounds but I cannot seem to get it working either the page doesn't load or it only center on one result and then I have to zoom out.
Here's for my setup for such case, Note that I use window here so I can access Google objects from any scope. You need to add each marker to mapBounds using extend() method and passing the position.
$(function(){
window.gMap = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 10,
center: {lat: 37.769, lng: -122.446}
});
var addresses = ["296 Gingerbread St", "383 Hoskins Ct", "1608 Liege Dr", "519 Mandalay Ct", "342 Pleasant Summit Dr", "1757 Quiver Point Ave", "174 Rising Mesa Ct", "26 Silica Sand St", "192 Thunder Plains Way", "277 Timber Hollow St", "367 Via Pacifico", "382 Washtenaw St"];
var timeOut = 0;
$.each(addresses, function(i, address){
setTimeout(function(){ addMarker(address) }, timeOut);
timeOut = timeOut+1600;
});
});
function addMarker(address) {
geoCoder.geocode({'address': address}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
gMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: gMap,
position: results[0].geometry.location,
});
markers.push(marker);
//extend the bounds to include each marker's position
mapBounds.extend(marker.position);
//now fit the map to the newly inclusive bounds
gMap.fitBounds(mapBounds);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
#map-canvas {
width:80%;
padding-left:15px;
padding-right:15px;
height:300px;
border:2px solid #e8e8e8;
border-radius:4px;
margin:auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function initMap() {
window.mapBounds = new google.maps.LatLngBounds();
window.geoCoder = new google.maps.Geocoder();
window.markers = [];
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
<div id="map-canvas"></div>
Related
I find a code that allows to get city information. How can I implement this with a simple map https://developers.google.com/maps/documentation/javascript/examples/map-simple?
I would only see this map on my app. the function is the same that is write on the code.
<!DOCTYPE html>
<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>Reverse Geocoding</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction(){
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
if (results[1]) {
//formatted address
alert(results[0].formatted_address)
//find country name
for (var i=0; i<results[0].address_components.length; i++) {
for (var b=0;b<results[0].address_components[i].types.length;b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
//this is the object you are looking for
city= results[0].address_components[i];
break;
}
}
}
//city data
alert(city.short_name + " " + city.long_name)
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
</body>
</html>
Use the code in this link
https://developers.google.com/maps/documentation/javascript/examples/map-geolocation.
Then you can copy your function codeLatLng on the new code and invoke it.
If you want show marker use this code:
// options for display map
var mapOptions = {
zoom: 14,
center: new google.maps.LatLng(lat, long),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
// color and image point
var pinColor = "ECECEC";
var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
pinShadow = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_shadow";
// display map and marker
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(lat, long),
icon: pinImage,
shadow: pinShadow,
title: 'Point 1'
});
This question already has an answer here:
How to connect two points in Google map..?
(1 answer)
Closed 8 years ago.
please help me on this, I really stuck on this!
my code is:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Geocoding service</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
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);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
var address2 = document.getElementById('address2').value;
geocoder.geocode( { 'address2': address2}, function(results2, status2) {
if (status2 == google.maps.GeocoderStatus.OK) {
var marker2 = new google.maps.Marker({
map: map,
position: results2[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
var myTrip = [address,address2];
var flightPath = new google.maps.Polyline({
path:myTrip,
strokeColor:"#00F",
strokeOpacity:0.8,
strokeWeight:2
});
flightPath.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="panel">
<input id="address" type="textbox" value="address 1">
<input id="address2" type="textbox" value="address 2">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map-canvas"></div>
</body>
</html>
I want to enter two address in the input, convert it to lat/long separately, put two markers on the map and draw a straight line between them!
my code is not working, it's displaying only the first address and that's all...
thank you in advance!
Well, it seems that you had at least syntax error (address2) because you defined:
geocoder.geocode( { 'address2': address2}, function(results2, status2) {
instead of:
geocoder.geocode( { 'address': address2}, function(results2, status2) {
However, you also had errors when defining the actual polyline, because geocoding is asynchronous you cant call creation of the polyline after geocode lines, instead you need to make separate method or similar callback functionality which is called when geocoding finishes. Otherwise, you are just handling undefined values.
Therefore, I decided to add method called displayMarkers() which is called from each geocode request which in turn checks whether all addresses is geocoded and acts accordingly. Here is the code with the changes: (It also works without page refresh, you can try seaching multiple addresses in a row).
var geocoder;
var map;
var geocodeMarkers = [];
var flightPath;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
// Emptying last addresses because of recent query
for(var i = 0; i < geocodeMarkers.length; i++) {
geocodeMarkers[i].setMap(null);
}
// Empty array
geocodeMarkers.length = 0;
// Empty flight route
if(typeof flightPath !== "undefined") {
flightPath.setMap(null);
flightPath = undefined;
}
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// Adding marker to geocodeMarkers
geocodeMarkers.push(
new google.maps.Marker({
position: results[0].geometry.location
})
);
// Attempting to display
displayMarkers();
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
var address2 = document.getElementById('address2').value;
geocoder.geocode( { 'address': address2 }, function(results2, status2) {
if (status2 == google.maps.GeocoderStatus.OK) {
// Adding marker to geocodeMarkers
geocodeMarkers.push(
new google.maps.Marker({
position: results2[0].geometry.location
})
);
// Attempting to display
displayMarkers();
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function displayMarkers() {
// If geocoded successfully for both addresses
if(geocodeMarkers.length === 2) {
// Bounds for the markers so map can be placed properly
var bounds = new google.maps.LatLngBounds(
geocodeMarkers[0].getPosition(),
geocodeMarkers[1].getPosition()
);
// Fit map to bounds
map.fitBounds(bounds);
// Setting markers to map
geocodeMarkers[0].setMap(map);
geocodeMarkers[1].setMap(map);
flightPath = new google.maps.Polyline({
path: [geocodeMarkers[0].getPosition(), geocodeMarkers[1].getPosition()],
strokeColor:"#00F",
strokeOpacity:0.8,
strokeWeight:2,
map: map
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
Working jsfiddle example: js fiddle demonstration 1
Edit:
After further comments, author of this topic wanted to center map on first geocoded marker. It is accomplished by changing following lines:
// Bounds for the markers so map can be placed properly
var bounds = new google.maps.LatLngBounds(
geocodeMarkers[0].getPosition(),
geocodeMarkers[1].getPosition()
);
// Fit map to bounds
map.fitBounds(bounds);
To:
// Center map to first geocoded location
map.setCenter(geocodeMarkers[0].getPosition());
Working jsfiddle for this: js fiddle demonstration 2
I have this on the of my .php file
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 15,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
and along the page I have the div in a modal
<div id="map-canvas"></div>
But the map does not show in the modal... I get no errors on Opera Console and when I try to call the functions [initialize() and or codeAddress("Spain")] through the console it says undifined
I've created a page only for the map for testing and it worked fine.
Any ideas?
==EDIT==
After adding the height to my css file the map is shown with some problems
http://postimg.org/image/mhj9awdez/
Only after a second initialization the map is shown correctly (the initialization must be done with the modal open)
you need to call initialize() function after the loading the js file ...
i think this will help you
<https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&' +
'callback=initialize';>>
<!DOCTYPE html>
<html>
<head>
<title>Asynchronous Loading</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script>
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&' +
'callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript;
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
I've heard that it is possible to submit an Address instead of Longitude and Latitude and this would be much more feasible for my system. The user has to input their address when creating their profile and their profile afterwards will then display a Google Maps of their house. I currently have the Google Maps API working perfectly with Longitude and Latitude:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="css.css" />
<title>Login Page</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=MYKEY&sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(52.640143,1.28685),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(52.640143,1.28685),
map: map,
title: "Mark On Map"
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
Please could somebody assist me to alter my code so that it enables the Google Maps API to request an Address in its place because I want to read the Address of the user directly from mySQL database.
See this example, initializes the map to "San Diego, CA".
Uses the Google Maps Javascript API v3 Geocoder to translate the address into coordinates that can be displayed on the map.
<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>Google Maps JavaScript API v3 Example: Geocoding Simple</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
var address ="San Diego, CA";
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
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);
if (geocoder) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
var infowindow = new google.maps.InfoWindow(
{ content: '<b>'+address+'</b>',
size: new google.maps.Size(150,50)
});
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title:address
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
} else {
alert("No results found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%">
</body>
</html>
working code snippet:
var geocoder;
var map;
var address = "San Diego, CA";
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
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);
if (geocoder) {
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
var infowindow = new google.maps.InfoWindow({
content: '<b>' + address + '</b>',
size: new google.maps.Size(150, 50)
});
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: address
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
} else {
alert("No results found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
}
<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas" ></div>
You can parse the geolocation through the addresses.
Create an Array with jquery like this:
//follow this structure
var addressesArray = [
'Address Str.No, Postal Area/city'
]
//loop all the addresses and call a marker for each one
for (var x = 0; x < addressesArray.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addressesArray[x]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
//it will place marker based on the addresses, which they will be translated as geolocations.
var aMarker= new google.maps.Marker({
position: latlng,
map: map
});
});
}
Also please note that Google limit your results if you don't have a business account with them, and you my get an error if you use too many addresses.
Geocoding is the process of converting addresses (like "1600 Amphitheatre Parkway, Mountain View, CA") into geographic coordinates (like latitude 37.423021 and longitude -122.083739), which you can use to place markers or position the map.
Would this be what you are looking for: Contains sample code
https://developers.google.com/maps/documentation/javascript/geocoding#GeocodingRequests
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == 'OK') {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
<body onload="initialize()">
<div id="map" style="width: 320px; height: 480px;"></div>
<div>
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Encode" onclick="codeAddress()">
</div>
</body>
Or refer to the documentation https://developers.google.com/maps/documentation/javascript/geocoding
Thought I'd share this code snippet that I've used before, this adds multiple addresses via Geocode and adds these addresses as Markers...
var addressesArray = [
'Address Str.No, Postal Area/city',
//follow this structure
]
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 12.7826,
lng: 105.0282
},
zoom: 6,
gestureHandling: 'cooperative'
});
var geocoder = new google.maps.Geocoder();
for (i = 0; i < addressArray.length; i++) {
var address = addressArray[i];
geocoder.geocode({
'address': address
}, function(results, status) {
if (status === 'OK') {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
center: {
lat: 12.7826,
lng: 105.0282
},
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
I used this example
example to create my code to find an address from lat. and long. coordinates.
The problem is that also with the correct coordinates, I find the postcode and not the address. Instead in the example, it can find the address.
I tried also to use the inverse method. I used coordinates that I found with the address, but they give me the postcode and not the address again.
Where am I wrong?
My code is the following:
<!DOCTYPE html>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<HTML>
<HEAD>
<script type="text/javascript" src="jquery.js"></script>
<META NAME="GENERATOR" Content="AlterVista - Editor HTML">
<title>LowPricePetrol</title>
<link rel="stylesheet" type="text/css" href="homeformat.css"/>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/">
</script>
<script type="text/javascript">
var geocoder;
var map;
var lat_;
var lng_;
var contentString="";
var infowindow = null;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(mia_posizione);
}else{
alert('La geo-localizzazione NON รจ possibile');
}
function initialize() {
infowindow = new google.maps.InfoWindow();
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.730885,-73.997383);
var mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
function mia_posizione(position) {
var lat_gl = position.coords.latitude;
var lon_gl = position.coords.longitude;
var latlng = new google.maps.LatLng(lat_gl , lon_gl );
alert(latlng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
alert(results[1].formatted_address);
map.setZoom(11);
marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
</script>
</HEAD>
<BODY onload="initialize();">
<div class="mapbox" id="map_canvas" style="width:700px; height:350px" ></div>
</BODY>
</HTML>
Below is the complete working example with the DEMO added at JSFIDDLE:
<script type="text/javascript">
function showAddress() {
var map,marker,infoWindow, geocoder;
var markerPoint = new google.maps.LatLng(12.397,78.644);
var mapOptions = {
center: new google.maps.LatLng(12.397,73.644),
zoom:5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
google.maps.event.addListener(map,'click',function(e) {
getAddress(e.latLng);
});
function getAddress(latLng) {
if(!geocoder) {
geocoder = new google.maps.Geocoder();
}
var geocoderRequest = {
latLng:latLng
}
geocoder.geocode(geocoderRequest, function(results, status) {
if(!infoWindow) {
infoWindow = new google.maps.InfoWindow();
}
infoWindow.setPosition(latLng);
var content = "<h2>Position :" +latLng.toUrlValue()+ "</h2>"
if(status == google.maps.GeocoderStatus.OK) {
for(var i =0;i <results.length; i++) {
if(results[0].formatted_address) {
content += i + ". " +results[i].formatted_address + "<br />";
}
}
}
else {
content += "<p>Either you clicked on Ocean or a Politically disputed Area. Status = " + status + "</p>"
}
infoWindow.setContent(content);
infoWindow.open(map)
});
}
}
</script>
DEMONSTRATION
Clicking on a Map will generate an InfoWindow and this infowindow will have the address of the place clicked, based on reverse geocoding.