autocomplete the data for Reverse Geocoding without manual input - html

this is the Reverse Geocoding from google api maps.My question is..
It is possible to remove Or HIDE the <div id="panel"> and get the data from current user location,without user need to press the button to Reverse Geocoding?
I want only to show the address of the user and NO the altitude & longitude..
thank you
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Reverse Geocoding</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"></script>
<script>
var geocoder;
var map;
var infowindow = new google.maps.InfoWindow();
var marker;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.730885,-73.997383);
var mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: 'roadmap'
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeLatLng() {
var input = document.getElementById('latlng').value;
var latlngStr = input.split(',', 2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(11);
marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style>
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
width: 350px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
#latlng {
width: 225px;
}
</style>
</head>
<body>
<div id="panel">
<input id="latlng" type="text" value="40.714224,-73.961452">
<input type="button" value="Reverse Geocode" onclick="codeLatLng()">
</div>
<div id="map-canvas"></div>
</body>
</html>

Yes you can.
I hope you're aware of HTML5 Geolocation, which will help you to get the current position of user.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
revereGeoCode(position.coords.latitude, position.coords.longitude);
});
} else {
// make sure to handle the failure
}
Using this apply you concept and get rid of the manually obtaining the lat and lng.
Complete code will be like below
var geocoder;
var map;
var marker;
var infowindow = new google.maps.InfoWindow();
function initializeMap() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
revereGeoCode(position.coords.latitude, position.coords.longitude);
});
} else {
console.log("er")
// make sure to handle the failure
}
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(40.730885, -73.997383),
mapTypeId: 'roadmap'
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function revereGeoCode(lat, lng) {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({
'latLng': latlng
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
// place your marker coding
map.setZoom(11);
marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initializeMap);
JSFiddle

Related

How do I stop the Google Maps API from automatically refreshing?

Current behaviour: The page constantly refreshes my location and the entire map.
Desired behaviour: I only want to find and display the current location once, not continuously.
How can I achieve this?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>whereami</title>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript" src="cordova.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key= xyz " type="text/javascript"></script>
<script type="text/javascript">
function onSuccess(position) {
var lat=position.coords.latitude;
var lang=position.coords.longitude;
var myLatlng = new google.maps.LatLng(lat,lang);
var mapOptions = {zoom: 17,center: myLatlng}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({position: myLatlng,map: map});
}
function onError(error) {}
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 0 });
google.maps.event.addDomListener(window, 'load', onSuccess);
</script>
</head>
<body>
<div id="geolocation"></div>
<div id="map-canvas"></div>
</body>
</html>
Don't keep recreating the map. Create the map once (in an "initMap" function), center the map an place the marker in the watchPosition callback function.
jsfiddle
// global variables
var map, marker, polyline;
function initMap() {
// initialize the global map variable
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {
lat: 0,
lng: 0
},
zoom: 1
});
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, {
timeout: 5000
});
}
google.maps.event.addDomListener(window, 'load', initMap);
function onSuccess(position) {
var lat = position.coords.latitude;
var lang = position.coords.longitude;
var myLatlng = new google.maps.LatLng(lat, lang);
map.setCenter(myLatlng);
map.setZoom(18);
if (marker && marker.setPosition)
marker.setMap(myLatlng); // move the marker
else // create a marker
marker = new google.maps.Marker({
position: myLatlng,
map: map
});
}
function onError(error) {
console.log('ERROR(' + error.code + '): ' + error.message);
}
html {
height: 100%;
width: 100%;
}
body {
height: 100%;
width: 100%;
margin: 0;
padding: 0
}
#map-canvas {
height: 100%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="geolocation"></div>
<div id="map-canvas"></div>

Looking for Google API to pull near by locations, facilities based on Pincode

Can anybody help me with a Google API which get me all surrounding information based on Pincode as an input.
Basically, if I input Pincode number then API should return all shopping malls, bridges, hospitals, hotels etc. I want to be able to store these information in database.
Please share your thoughts.
I hope following code will help you. What it does? 1. Take your pincode from input field, geocode it. 2. From the result of geocode, it applies on places api to find nearby stores in 500 meter radius.
<!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: 800px;
widows: 700px;
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&signed_in=true&libraries=places"></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
});
var request = {
location: results[0].geometry.location,
radius: '500',
types: ['store']
}; //500 meters and stores only
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}});}
function callback(results, status) {
console.log(status, results);
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
//createMarker(results[i]);
var marker = new google.maps.Marker({
map:map,
position: place.geometry.location
})
}}}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="panel">
<input id="address" type="textbox" value="452009">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map-canvas"></div></body></html>
If you have any more queries, please comment, we can work on it.
Regards,
Suyash

how to remove previous marker in google map

This is my geocoder google map code
MY code work when i change the select option
the marker is add in map, when i select multiple places,
i want to remove previous marker.
<!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(9.9252007,78.1197754);
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);
}}); }
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head><body>
<div align="center" verticle-align="ce">
<form method="get" action="">
<select name="address" id="address" onChange="codeAddress()" >
<option value="chennai,india">chennai,india</option>
<option value="madurai,india">madurai,india</option>
<option value="bangalore,india">bangalore,india</option>
<option value="delhi,india">Delhi</option>
</select>
</form> </div>
<div id="map-canvas" style="width:750px;height:500px;"></div>
</body></html>
working of the code:
when i load the page ,it automatic load the initial place, i change the option value it will load the choose one.
Make marker as global variable, move marker definition to initialize() function and on change of selection set position using marker.setPosition():
var geocoder;
var map;
var marker;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(9.9252007,78.1197754);
var mapOptions = {
zoom: 8,
center: latlng
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
marker = new google.maps.Marker({
map: map
});
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var position = results[0].geometry.location;
map.setCenter(position);
marker.setPosition(position);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
See example at jsbin.

Google Map Event listener

I have a problem in event listener. I created 'click' event listener in 'map', every time the user clicks on the map a new marker is created. Each marker has it's own infobox that contains a link to remove the marker.
The problem is when i click the remove link inside the infobox, the map's click event is always triggered. The marker is successfully removed but the it creates a new marker. How can i fix this? I just want to remove the marker.
here's the code:
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=123456778&sensor=true"></script>
<script type="text/javascript" src="infobox.js"></script>
<script type="text/javascript">
var map;
var markers = [];
var infowindows = [];
var marker_cnt = 0;
var marker_icons = { 'mall' : 'mall.png', 'train_station': 'train.png','park' : 'park.png', 'bank':'bank.png'};
var infoWindow;
var places = [
['Central','mall',1.2892612468505713,103.84759068489075,'central mall'] ,
['Dhoby Ghaut','train_station',1.298550049775337,103.84589552879333,'Dhoby Ghaut'] ,
['Outram Station', 'train_station',1.2812595487889478, 103.83896470069885,'Outram Station'],
['City Hall', 'bank', 1.2932084559435784, 103.85241866111755,'City Hall Station'],
['Little India Station', 'train_station', 1.3071308997488136, 103.84971499443054,'Little India Station'],
['Emily Park', 'park', 1.3071308997488136, 103.84971499443054,'Emily Park']
];
var myOptions = {
content: 'loading...'
,boxStyle: {
background: "#ccc"
,opacity: 1
,width: "280px"
,height: "100px"
,padding: "10px"
}
,closeBoxMargin: "10px 2px 2px 2px"
,closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif"
,pane: "floatPane"
,enableEventPropagation: false
};
var infowindow = new InfoBox(myOptions);
google.maps.event.addListener(infowindow, 'click', function () {
console.log('aaaa');
});
function initialize()
{
var myLatlng = new google.maps.LatLng(1.2892826990902386,103.84409308433533);
var myOptions = {
zoom: 16,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, 'click', function(event){
placeMarker(event.latLng,event.getPosition);
});
loadMarkers();
}
function loadMarkers()
{
for(var i = 0 ; i < places.length; i++)
{
var spot = places[i];
var spot_latlng = new google.maps.LatLng(spot[2],spot[3]) ;
var marker = new google.maps.Marker({
map:map,
draggable:false,
position: spot_latlng,
title: spot[0],
icon: marker_icons[spot[1]],
html: '<h1>'+spot[4]+'</h1> website '
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
}
}
function unloadMarkers()
{
for(var i = 0; i < markers.length; i++)
{
markers[i].setMap(null);
}
}
function setMapCenter(index)
{
var spot = places[index];
var spot_latlng = new google.maps.LatLng(spot[2],spot[3]);
infowindow.setContent(markers[index].html = spot[4]);
infowindow.open(map, markers[index]);
map.setCenter(spot_latlng);
}
function placeMarker(location,position)
{
marker = new google.maps.Marker({
map:map,
draggable:true,
animation: google.maps.Animation.DROP,
position: location,
html: 'delete marker <br/> '+ location
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
google.maps.event.addListener(marker,'dragend',function(){
var html_content = 'delete marker <br/>'+ this.position;
this.html=html_content;
infowindow.setContent(this.html);
infowindow.open(map,this);
});
google.maps.event.addListener(marker,'dragstart',function(){
infowindow.close(map,this);
});
}
function removeMarker(index)
{
markers[index].setMap(null);
infowindow.close(map, markers[index]);
infowindows[index].close();
return false;
}
</script>
<style type="text/css">
html{
font:12px Arial, Helvetica, sans-serif;
color:#333;
padding:0;
margin:0;
}
.listmenu{
height:300px;
}
.listmenu ul {
margin: 0 0 5px 0;
padding: 0 0 2px 0;
list-style-type: none;
width:185px;
}
.listmenu li a {
color: #333;
display: block;
height: 16px;
padding: 4px 0 4px 14px;
text-decoration: none;
font-weight:bold;
background-color:#fff;
}
.listmenu li a:hover {
background-color: #666;
color:#fff;
}
</style>
<body onload="initialize()">
<div id="map_canvas" style="width:1000px; height:300px; border: 3px solid #666"></div>
pass the click-event as argument to removeMarker()
marker = new google.maps.Marker({
map:map,
draggable:true,
animation: google.maps.Animation.DROP,
position: location,
html: '<a href="#" onclick="removeMarker('+ (markers.length) +',event)">\
delete marker</a> <br/> '+ location
});
Then you'll be able to stop the propagation of the event:
function removeMarker(index,event)
{
try{event.cancelBubble=true;}//IE
catch(e){event.stopPropagation();}//others
markers[index].setMap(null);
infowindow.close(map, markers[index]);
return false;
}
Thanks for the reply. I already solved this problem. I fixed it by removing "onclick" and placing javascript to href <a href='javascript: removeMarker(index)'> remove </a>

google maps API v3 put draggable maker

this my code,
function initialize() {
if (GBrowserIsCompatible()) {
var city = 'battaramulla';
var center = '';
var map = new GMap2(document.getElementById("map_canvas"));
map.setUIToDefault();
var geocoder = new GClientGeocoder();
geocoder.getLatLng(city, function (point) {
if (!point) {
alert(city+" not found :-(");
} else {
alert(city+" "+point+" found :-)");
map.setCenter(point, 8);
}
});
}
}
I want to add drggable maker to this city(point). Please help me. thanks.
You can try this complete example...
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">`enter code here`
var geocoder = new google.maps.Geocoder();
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
function updateMarkerPosition(latLng) {
document.getElementById('info').innerHTML = [
latLng.lat(),
latLng.lng()
].join(', ');
}
function updateMarkerAddress(str) {
document.getElementById('address').innerHTML = str;
}
function initialize() {
var latLng = new google.maps.LatLng(-34.397, 150.644);
var map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 8,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latLng,
title: 'Point A',
map: map,
draggable: true
});
// Update current position info.
updateMarkerPosition(latLng);
geocodePosition(latLng);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function() {
updateMarkerAddress('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerStatus('Dragging...');
updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
});
}
// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<style>
#mapCanvas {
width: 500px;
height: 400px;
float: left;
}
#infoPanel {
float: left;
margin-left: 10px;
}
#infoPanel div {
margin-bottom: 5px;
}
</style>
<div id="mapCanvas"></div>
<div id="infoPanel">
<b>Marker status:</b>
<div id="markerStatus"><i>Click and drag the marker.</i></div>
<b>Current position:</b>
<div id="info"></div>
<b>Closest matching address:</b>
<div id="address"></div>
</div>
</body>
</html>
Use geocoder to find the closest address.
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}