Get latitude and longitude from search box - javascript

I know many thread discuss this but my code still doesn't work.
I'm using google places searchBox API.
My code:
function initMap(){
var map = new google.maps.Map(document.getElementById('peta'), {
center: {lat: -34.397, lng: 150.644},
zoom: 16
});
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Your Location.');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
var input = document.getElementById('alamat');
var searchBox = new google.maps.places.SearchBox(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
var markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
document.getElementById('x').innerHTML(places.geometry.location.lat());
});
}
link script:
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap&libraries=places"></script>
html:
<div id="peta" style="width:500px;height:380px;"></div>
<input type="text" id="x" readonly="readonly" name="x">
i put document.getElementById on my textbox but it still doesn't show the latitude. Where i should put this code?
in other thread:
var location= places.geometry.location;
var lat = location.lat();
but it's not working. How do I solve the problem?

Is your element #x an input text box?
If so try:
document.getElementById('x').value = places.geometry.location.lat();
That will add the latitude to the value of the input text box.
Is this what you are trying to achieve?

I've solve the problem.
as #Dammeul said, i place the
document.getElementById('x').value = place.geometry.location.lat();
inside of places.forEach(function (place))
Hope this helpful.

It will convert the address into latitude and longitude and also show the address in the map with the marker..You have just add your map API key
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
function initMap() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(23.684994, 90.35633099999995);
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);
}
});
}
function showResult(result) {
document.getElementById('latitude').value = result.geometry.location.lat();
document.getElementById('longitude').value = result.geometry.location.lng();
}
function getLatitudeLongitude(callback, address) {
address = address || 'Dhaka,Bangladesh';
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
callback(results[0]);
}
});
}
}
var button = document.getElementById('show');
button.addEventListener("click", function () {
var address = document.getElementById('address').value;
getLatitudeLongitude(showResult, address)
});
</script>
<!doctype html>
<html>
<head>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 400px;
width: 800px;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body onload="initMap()">
<div>
<div id="map" style="width: 320px; height: 480px;"></div>
<div>
<input id="address" type="textbox" value="">
<input type="button" id="show" value="Show" onclick="codeAddress()">
</div>
<div>
<p>Latitude:
<input type="text" id="latitude" readonly />
</p>
<p>Longitude:
<input type="text" id="longitude" readonly />
</p>
</div>
</body>
</html>

const { GoogleMap, LoadScript } = require("../../");
const ScriptLoaded = require("../../docs/ScriptLoaded").default;
const mapContainerStyle = {
height: "400px",
width: "800px"
};
const center = {
lat: 38.685,
lng: -115.234
};
const onLoad = ref => this.searchBox = ref;
const onPlacesChanged = () => {
x = this.searchBox.getPlaces()
console.log(x[0]["geometry"]["location"].lat())
}
<ScriptLoaded>
<GoogleMap
id="searchbox-example"
mapContainerStyle={mapContainerStyle}
zoom={2.5}
center={center}
>
<StandaloneSearchBox
onLoad={onLoad}
onPlacesChanged={
onPlacesChanged
}
>
<input
type="text"
placeholder="Customized your placeholder"
style={{
boxSizing: `border-box`,
border: `1px solid transparent`,
width: `240px`,
height: `32px`,
padding: `0 12px`,
borderRadius: `3px`,
boxShadow: `0 2px 6px rgba(0, 0, 0, 0.3)`,
fontSize: `14px`,
outline: `none`,
textOverflow: `ellipses`,
position: "absolute",
left: "50%",
marginLeft: "-120px"
}}
/>
</StandaloneSearchBox>
</GoogleMap>
</ScriptLoaded>
Hi, i tried this, and it works, i get the lat and long, I am using react+searchboxAPI please feel free to follow up, here is the documentation, I realised that you cant do x["geometry"]["location"].lat(), instead you'll need to iterate through each of the places that have been returned, to test it, I did
console.log( x[0]["geometry"]["location"].lat() ) just to get the first result.You can use the js map function or iterate through the array of 20 by using a for loop.. cheers
https://react-google-maps-api-docs.netlify.app/#!/StandaloneSearchBox/1

Related

Google Maps places API - How to get Country, Postal-code, Number, Website URL with Google map search box on multiple results

I am using google map search box with Google Maps places API to get multiple results like stores and places etc.
It's working fine and I am getting addresses and Latitude - Longitude but how can I get rest of details if available like Country, Postal-code, Website URL, Contact number and Ratings.
Here is my code, any help or suggestion 'll be appreciated.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=My_API_Key&libraries=places&callback=initAutocomplete" async defer"></script>
<style>
#wrapper {width:1280px; margin:0 auto;}
#map {
width: 100%;
height:300px;
}
.controls {
margin-top: 10px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#searchInput {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 50%;
}
#searchInput:focus {
border-color: #4d90fe;
}
ul {margin:30px 100px;}
li {margin:5px 0;}
li span {font-weight:bold; padding-left:5px;}
</style>
</head>
<body>
<script>
// This example adds a search box to a map, using the Google Place Autocomplete
// feature. People can enter geographical searches. The search box will return a
// pick list containing a mix of places and predicted search terms.
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -33.8688,
lng: 151.2195
},
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Create the search box and link it to the UI element.
var input = document.getElementById('searchInput');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function () {
searchBox.setBounds(map.getBounds());
});
var markers = [];
// [START region_getplaces]
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function () {
$('#mapContent').html("");
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function (marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function (place) {
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
var marker = new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function (evt) {
//document.getElementById('coordinates').value = marker.getPosition().toUrlValue(6);
alert(this.placeId)
});
markers.push(marker);
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
$('#mapContent').append('<ul id="geoData">' +
'<li>Full Address: <span id="location">'+ place.formatted_address +'</span></li>'+
'<li>Postal Code: <span id="postal_code"></span></li>'+
'<li>Country: <span id="country">'+ +'</span></li>'+
'<li>Latitude: <span id="lat">'+ place.geometry.location.lat() +'</span></li>'+
'<li>Longitude: <span id="lon">'+ place.geometry.location.lng() +'</span></li>'+
'<li>Website: <span id="website"></span></li>'+
'<li>Contact Number: <span id="number"></span></li>'+
'<li>Rating: <span id="rating"></span></li>'+
'</ul>');
});
map.fitBounds(bounds);
});
// [END region_getplaces]
}
</script>
<!--<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map"></div>-->
<div id=wrapper>
<input id="searchInput" class="controls" type="text" placeholder="Enter a location">
<div id="map"></div>
<div id="mapContent">
</div>
</div>
</body>
</html>
Google Maps places gives you a reference, and an ID. You can use that id to request extra details.
I added this to your code:
// make sure this variable is accesible where you need it (scope)
var service = new google.maps.places.PlacesService(map);
then, for example the website:
// request details
service.getDetails(place, function(result, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
console.error(status);
return;
}
$('#website').html('<a target="_blank" href="'+ result.website +'">'+ result.website +'</a>');
});
You can get extra details, see https://developers.google.com/maps/documentation/javascript/places
Now, another problem you face, is that ID must be unique !!!
So you must not put that in a foreach loop. My solution will only fill in the first occurence of id="website"
places.forEach(function (place) {
...
<span id="website"></span>
...
}
You should solve this first, before continueing. Use class instead of id, for all things inside for-loops
Here is the full script
<script>
// This example adds a search box to a map, using the Google Place Autocomplete
// feature. People can enter geographical searches. The search box will return a
// pick list containing a mix of places and predicted search terms.
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -33.8688,
lng: 151.2195
},
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Create the search box and link it to the UI element.
var input = document.getElementById('searchInput');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function () {
searchBox.setBounds(map.getBounds());
});
var markers = [];
// srvice for PLACE details
var service = new google.maps.places.PlacesService(map);
// [START region_getplaces]
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function () {
$('#mapContent').html("");
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function (marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function (place) {
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
var marker = new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function (evt) {
//document.getElementById('coordinates').value = marker.getPosition().toUrlValue(6);
alert(this.placeId)
});
markers.push(marker);
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
$('#mapContent').append('<ul id="geoData">' +
'<li>Full Address: <span id="location">'+ place.formatted_address +'</span></li>'+
'<li>Postal Code: <span id="postal_code"></span></li>'+
'<li>Country: <span id="country">'+ +'</span></li>'+
'<li>Latitude: <span id="lat">'+ place.geometry.location.lat() +'</span></li>'+
'<li>Longitude: <span id="lon">'+ place.geometry.location.lng() +'</span></li>'+
'<li>Website: <span id="website"></span></li>'+
'<li>Contact Number: <span id="number"></span></li>'+
'<li>Rating: <span id="rating"></span></li>'+
'</ul>');
// request details
service.getDetails(place, function(result, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
console.error(status);
return;
}
$('#website').html('<a target="_blank" href="'+ result.website +'">'+ result.website +'</a>');
});
});
map.fitBounds(bounds);
});
// [END region_getplaces]
}
</script>

I can't change the size of the radius using input box and button for the user Google Map API

I have the following code and I want to set and change the circle's radius through user's input using input box and button. Any help will be appreciated. EDIT. This is the revised code based on the example provided below but still won't work for me. Every help will be appreciated.
<apex:page controller="GeoLocatorController" sidebar="false" showheader="false">
<head>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { width:100%;height:80%; }
.controls
</style>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBJkHXEVXBSLY7ExRcxoDxXzRYLJHg7qfI"></script>
<script>
var circle;
function initialize() {
//Setting default center of the system
var mapCenter = {
center: new google.maps.LatLng(36.2048, 138.2529),
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"), mapCenter);
//Get User's Geolocation and Set as the Center of the System
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
userLat = position.coords.latitude;
userLng = position.coords.longitude;
userLoc = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(userLoc);
//User Marker's Image
var image = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
//Create Marker for the User's Location
var centerLoc = new google.maps.Marker({
position : new google.maps.LatLng(userLat, userLng),
map : map,
icon: image,
title : 'Your Position!',
draggable : true,
animation: google.maps.Animation.DROP
});
//Create Circle and Bind it to User's Location
circle = new google.maps.Circle({
map: map,
radius: 100, // 10 miles in metres
fillColor: '#AA0000'
});
circle.bindTo('center', centerLoc, 'position');
marker.setMap(map);
});
function updateRadius(){
var rad = document.getElementById("value_rad").value;
circle.setRadius(parseFloat(rad));
}
}
loadHotels();
}
//Load Records from Cloud
function loadHotels({Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.GeoLocatorController.findAll}',
function(result, event){
if (event.status) {
for (var i=0; i<result.length; i++) {
var id = result[i].Id;
var name = result[i].Name;
var lat = result[i].Location__Latitude__s;
var lng = result[i].Location__Longitude__s;
addMarker(id, name, lat, lng);
}
} else {
alert(event.message);
}
},
{escape: true}
);
}
//Create Markers for the Records from the Cloud
function addMarker(id, name, lat, lng) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map,
title: name,
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
console.log()
</script>
</head>
<body>
<div id="googleMap" style="width:100%;height:80%;"/>
<input id="value_rad" />
<input id="radius" type="button" value="Search" onclick="updateRadius()"/>
</body>
</apex:page>
See this code (it's work), and adapt your code
var user_lat;
var user_lng;
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
var crd = pos.coords;
user_lat = crd.latitude;
user_lng = crd.longitude;
};
function error(err) {
alert('ERROR(' + err.code + '): ' + err.message);
};
var circle;
var myCenter;
function initialize() {
navigator.geolocation.getCurrentPosition(success, error, options);
myCenter = new google.maps.LatLng(user_lat, user_lng);
var mapProp = {
center: myCenter,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var marker = new google.maps.Marker({
position: myCenter,
});
circle = new google.maps.Circle({
map: map,
radius: 100, // 10 miles in metres
fillColor: '#AA0000',
center: myCenter
});
marker.setMap(map);
}
function updateRadius(){
var rad = document.getElementById("value_rad").value;
circle.setRadius(parseFloat(rad));
}
google.maps.event.addDomListener(window, 'load', initialize);
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBJkHXEVXBSLY7ExRcxoDxXzRYLJHg7qfI"></script>
<div id="googleMap" style="width:500px;height:380px;"></div>
<input id=value_rad />
<input id="radius" type="button" value="test" onclick="updateRadius()"/>

trouble getting my mouseover on markers to work

I have created my code below with the mouseover affect at the end, but it does not work. Have I put it in the wrong place? I just can't seem to get it to work. Eventually I would like to get a certain type of info displayed on them but each step at a time, trying to get the basic to work first.
<!DOCTYPE html>
<html>
<head>
<!-- Google Maps and Places API -->
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
//declare namespace
var up206b = {};
//declare map
var map;
function trace(message)
{
if (typeof console != 'undefined')
{
console.log(message);
}
}
up206b.initialize = function()
{
var latlng = new google.maps.LatLng(52.136436, -0.460739);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
var geocoder = new google.maps.Geocoder();
up206b.geocode = function()
{
var addresses = [ $('#address').val(), $('#address2').val()];
addresses.forEach(function(address){
if(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);
}
});
}
});
}
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
marker.addListener('mouseover', function() {
infowindow.open(map, this);
});
marker.addListener('mouseout', function() {
infowindow.close();
});
</script>
</head>
<body onload="up206b.initialize()">
<div style="top: 0; right: 0; width:380px; height: 500px; float:right;padding-left:10px; padding-right:10px;">
<h1 align="center">Map Search</h1>
<div style="border:1px solid #ccc; background:#e5e5e5; padding:10px;" >
<form >
<br>
Location 1 <input type="text" id="address">
<br>
<br>
Location 2
<input type="text" id="address2">
<br>
<br>
<input type="button" value="Submit" onClick="up206b.geocode()">
</form>
</div>
</div>
<div id="map_canvas" style="height: 500px; width: 500px; float:right"></div>
You need to:
define contentString
associate the marker with the infowindow content. One way of doing that is with anonymous function closure as in this related question Google Maps JS API v3 - Simple Multiple Marker Example, or with an explicit createMarker function as in my example below.
Note: This approach will only work for approximately 10 addresses, after which it will run into the Geocoder rate limits.
function createMarker(latlng, html, map) {
var infowindow = new google.maps.InfoWindow({
content: html
});
var marker = new google.maps.Marker({
map: map,
position: latlng
});
marker.addListener('mouseover', function() {
infowindow.open(map, this);
});
marker.addListener('mouseout', function() {
infowindow.close();
});
}
proof of concept fiddle
code snippet:
var markers = [];
function createMarker(latlng, html, map) {
var infowindow = new google.maps.InfoWindow({
content: html
});
var marker = new google.maps.Marker({
map: map,
position: latlng
});
marker.addListener('mouseover', function() {
infowindow.open(map, this);
});
marker.addListener('mouseout', function() {
infowindow.close();
});
markers.push(marker);
}
//declare namespace
var up206b = {};
//declare map
var map;
function trace(message) {
if (typeof console != 'undefined') {
console.log(message);
}
}
up206b.initialize = function() {
var latlng = new google.maps.LatLng(52.136436, -0.460739);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
up206b.geocode();
}
var geocoder = new google.maps.Geocoder();
up206b.geocode = function() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
var bounds = new google.maps.LatLngBounds();
var addresses = [$('#address').val(), $('#address2').val()];
addresses.forEach(function(address) {
if (address) {
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
createMarker(results[0].geometry.location, address, map);
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
});
}
google.maps.event.addDomListener(window, "load", up206b.initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="address" value="New York, NY" />
<input id="address2" value="Newark, NJ" />
<input type="button" value="Submit" onClick="up206b.geocode()">
<div id="map_canvas"></div>

google api reverse geocode

I Have a google map on my site. Users can drag the marker and the map will input the lat and lon into a form for me. See code below. I want to be able to get the address from the lat and lon and put it into my form at "locationbox".
<script src="multi_step_form.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
<script type="text/javascript">
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(49.25302534866034,-102.04825518471148);
var myOptions = {
zoom: 3,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.HYBRID
}
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, 'dragend', function (event) {
document.getElementById("latbox").value = this.getPosition().lat();
document.getElementById("lngbox").value = this.getPosition().lng();
});
}
</script>
I have another bit of code to look up the address that I got from https://203luv.wordpress.com/2011/10/21/google-maps-javascript-v3-api-how-to-get-address-from-coordinates-latitude-longitude/ but I just can't figure out how to blend them together.
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
var lat = "12.1234";
var long = "98.7654";
var latlng = new google.maps.LatLng(sLat, sLong);
geocoder.geocode({"latLng":latlng},function(data,status){
if(status == google.maps.GeocoderStatus.OK){
var add = data[1].formatted_address; //this is the full address
alert(add);
for(var i=0; i<data[1].address_components.length; i++){
if(results[1].address_components[i].types[0] == "administrative_area_level_1"){
alert(results[1].address_components[i].short_name);
}
}
}
})
My html form looks like this
<div id="map_canvas" style="width: 450px; height: 450px; background-color: Black;"></div>
<div id="latlong">
<p><input size="20" type="text" id="latbox" name="lat" placeholder="Drag the marker on the map or type in the latitude"></p>
<p><input size="20" type="text" id="lngbox" name="lon" placeholder="Drag the marker on the map or type in the longitude"></p>
</div>
<input class="text_field" id="locationbox" name="location" placeholder="Location" type="text" >
Any help would be appreciated
I would suggest calling the reverse geocoder in the dragend event listener function:
google.maps.event.addListener(marker, 'dragend', function (event) {
document.getElementById("latbox").value = this.getPosition().lat();
document.getElementById("lngbox").value = this.getPosition().lng();
var latlng = this.getPosition();
geocoder.geocode({
"latLng": latlng
}, function (data, status) {
if (status == google.maps.GeocoderStatus.OK) {
var add = data[1].formatted_address; //this is the full address
// alert(add);
for (var i = 0; i < data[1].address_components.length; i++) {
if (data[1].address_components[i].types[0] == "administrative_area_level_1") {
document.getElementById('locationbox').value = data[1].address_components[i].short_name;
}
}
}
});
});
proof of concept fiddle
code snippet:
var map;
function initialize() {
var geocoder = new google.maps.Geocoder();
var myLatlng = new google.maps.LatLng(49.25302534866034, -102.04825518471148);
var myOptions = {
zoom: 3,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
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, 'dragend', function(event) {
document.getElementById("latbox").value = this.getPosition().lat();
document.getElementById("lngbox").value = this.getPosition().lng();
var latlng = this.getPosition();
geocoder.geocode({
"latLng": latlng
}, function(data, status) {
if (status == google.maps.GeocoderStatus.OK) {
var add = data[1].formatted_address; //this is the full address
// alert(add);
for (var i = 0; i < data[1].address_components.length; i++) {
if (data[1].address_components[i].types[0] == "administrative_area_level_1") {
document.getElementById('locationbox').value = data[1].address_components[i].short_name;
}
}
}
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas" style="width: 450px; height: 450px; background-color: Black;"></div>
<div id="latlong">
<p>
<input size="20" type="text" id="latbox" name="lat" placeholder="Drag the marker on the map or type in the latitude">
</p>
<p>
<input size="20" type="text" id="lngbox" name="lon" placeholder="Drag the marker on the map or type in the longitude">
</p>
</div>
<input class="text_field" id="locationbox" name="location" placeholder="Location" type="text">

Google Maps JavaScript API v3 drawing line between two location [duplicate]

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

Categories

Resources