How to find the exact location details from latitude and longitude? - google-maps

I tried using Google Maps API for 'Reverse Geocoding' to get the location by providing latitude and longitude. This gives the street address, city and country info. But I need to get the exact details like building name, shop name etc. For example, while querying the co-ordinates "72.9011206,19.0517508", Google Maps API gives "Plot No 5, VN Purav Marg, Borla, Union Park, Chembur, Mumbai, Maharashtra 400071, India". But I need to get the name of the shop "Barista Lavazza" as available in 'Google Earth' for the same co-ordinate details.

One option would be to use the Google Maps Javscript API Places library nearbySearch, search the returned results for the closest result to the requested position.
proof of concept fiddle
code snippet:
var map;
var infowindow;
var searchLoc = new google.maps.LatLng(19.0517508, 72.9011206);
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: searchLoc,
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
infowindow = new google.maps.InfoWindow();
var request = {
location: searchLoc,
radius: '50'
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var bounds = new google.maps.LatLngBounds();
var distMin = Number.MAX_VALUE;
var idxMin = -1;
for (var i = 0; i < results.length; i++) {
var place = results[i];
bounds.extend(results[i].geometry.location);
var distance = google.maps.geometry.spherical.computeDistanceBetween(results[i].geometry.location, searchLoc);
if (distance < distMin) {
distMin = distance;
idxMin = i;
}
}
var marker = createMarker(results[idxMin]);
google.maps.event.trigger(marker, 'click');
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent("<h2 style='color:blue'>"+place.name + "</h2><br>" + place.vicinity + "<br>" + marker.getPosition().toUrlValue(7));
infowindow.open(map, this);
});
return marker;
}
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?libraries=geometry,places"></script>
<div id="map_canvas"></div>

Related

PLACES API: Address returned by maps.google.com different from when invoked via API

When I pass the address to Google Maps .com in the browser, it returns a certain name of the address on the marker(as shown in fig -1). But when I pass the postal address using Google Place and Geocoder API’s, it returns me the address and place ID with the marker(as shown in fig-2) .
As shown in images the address values returned by MAPS application is different from the one’s I am getting through the API’s.
Is it some attribute of the API which gives the name of the building or centre situated at this address?
Is it some premium service that I need to buy in order to display the exact name of building at this address ?
I have tried with various attributes of the PLACES API but not getting the value I need. using PLACE API
var address = "1900 S Jackson Rd Suite 7 MCALLEN TX";
var map;
var marker;
var service;
var request;
function initialize() {
var geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map_canvas'),
{
center : {
lat : - 33.866, lng : 151.196
},
zoom : 15
});
if (geocoder) {
geocoder.geocode( {
'address' : address
},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
service = new google.maps.places.PlacesService(map);
console.log(results[0].place_id);
map.setCenter(results[0].geometry.location);
console.log('resulta ddre '+results[0].formatted_address);
service.getDetails( {
placeId : (results[0].place_id)
},
function (place, status) {
var infowindow = new google.maps.InfoWindow();
if (status === google.maps.places.PlacesServiceStatus.OK) {
console.log(status);
marker = new google.maps.Marker( {
map : map, position : place.geometry.location
});
console.log('<HTML ATT>'+ place.address_components+'Place ID: ' + place.place_id
+ '<Place Name>' + place.name
+ '<Formatted Address>' + place.formatted_address);
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + 'Place ID: ' + place.place_id + '<br>' + place.formatted_address +
'</div>');
infowindow.open(map, this);
});
}
});
};
}
});
}
}
When you search "1900 S Jackson Rd Suite 7 MCALLEN TX" on maps.google.com you get the location of "Pediatric Lung Center: Ayres Roberto A MD".
Please note that Geocoding service works only with street addresses, and businesses are excluded from the search. In your code you execute a geocoding request first so you get a different result. You have to execute places text search to get the same business as on maps.google.com.
Have a look at the following example:
code snippet:
var map;
var infowindow;
var address = "1900 S Jackson Rd Suite 7 MCALLEN TX";
function initMap() {
var m_center = {lat: 26.1817228, lng: -98.2098557};
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: m_center,
zoom: 16
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.textSearch({
query: address,
bounds: map.getBounds()
}, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
title: place.name
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<div id="map-canvas"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?v=3&libraries=places&callback=initMap"></script>

Pass Google Maps SearchBox result to Directions Service

After reading documentation for the SearchBox class, the Places library including the AutoComplete class, and the Directions service, I cannot figure out how to pass the address selected by a user from the SearchBox to the Directions service to draw the map. The map and marker display correctly, and the SearchBox displays and functions correctly. On the "place_change" event, though, nothing happens. My code:
var rawlatitude = <?php echo $loc_lat; ?>;
var rawlongitude = <?php echo $loc_long; ?>;
var latitude = parseFloat(rawlatitude);
var longitude = parseFloat(rawlongitude);
var latlong = new google.maps.LatLng(latitude,longitude);
google.maps.event.addDomListener(window, 'load',initMap(latitude,longitude));
function initMap(lat,lng) {
// instantiate directions service object
var directionsService = new google.maps.DirectionsService;
// create map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: latlong
});
// add marker
var marker = new google.maps.Marker({
position: latlong,
map: map
});
// put address search box into map
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// create directions renderer and bind it to map
var directionsDisplay = new google.maps.DirectionsRenderer({map: map});
// listen to and respond to address search
var onChangeHandler = function() {
var location = searchBox.getPlaces();
var start = location.place_id;
calculateAndDisplayRoute(directionsDisplay, directionsService, map, start);
};
google.maps.event.addListener(searchBox, 'place_change', onChangeHandler);
}
function calculateAndDisplayRoute(directionsDisplay, directionsService, map, start) {
directionsService.route({
origin: start,
destination: latlong,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if(status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
As Dr.Molle observed in his comment,
There is no place_changed-event for a SearchBox, it's an event for Autocomplete. The event for a SearchBox is called places_changed.
Also note that a SearchBox.getPlaces() returns an array with places
working fiddle
working code snippet:
var rawlatitude = 40.7127837;
var rawlongitude = -74.0059413;
var latitude = parseFloat(rawlatitude);
var longitude = parseFloat(rawlongitude);
var latlong = new google.maps.LatLng(latitude, longitude);
var viewport = {
"south": 40.4960439,
"west": -74.2557349,
"north": 40.91525559999999,
"east": -73.7002721
};
google.maps.event.addDomListener(window, 'load', function() {
initMap(40.735657, -74.1723667);
});
function initMap(lat, lng) {
// instantiate directions service object
var directionsService = new google.maps.DirectionsService;
// create map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: latlong
});
// add marker
var marker = new google.maps.Marker({
position: latlong,
draggable: true,
map: map
});
// put address search box into map
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input, {
bounds: viewport
});
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// create directions renderer and bind it to map
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
// listen to and respond to address search
var onChangeHandler = function() {
var locations = searchBox.getPlaces();
var start = locations[0].place_id;
var bounds = new google.maps.LatLngBounds();
bounds.extend(latlong);
bounds.extend(locations[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
position: locations[0].geometry.location,
map: map,
title: locations[0].name
})
calculateAndDisplayRoute(directionsDisplay, directionsService, map, start);
};
google.maps.event.addListener(searchBox, 'places_changed', onChangeHandler);
}
function calculateAndDisplayRoute(directionsDisplay, directionsService, map, start) {
directionsService.route({
origin: {
placeId: start
},
destination: {
location: latlong
},
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<input id="pac-input" />
<div id="map"></div>

How to use KML file in Google Maps for OFBiz?

I'm trying to use KML file in Google Maps in OFBiz framework for a web application.I'm inputing the co-ordinates value in a array(list). So, how can i begin using Kml file in Google Maps??
I have inserted code of google maps in .ftl file
function initialize() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'satellite'
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
// Multiple Markers
var markers = [
['London Eye, London', 51.503454,-0.119562],
['Palace of Westminster, London', 51.499633,-0.124755]
];
// Info Window Content
var infoWindowContent = [
['<div class="info_content">' +
'<h3>London Eye</h3>' +
'<p>The London Eye is a giant Ferris wheel situated on the banks of the River Thames. The entire structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft).</p>' + '</div>'],
['<div class="info_content">' +
'<h3>Palace of Westminster</h3>' +
'<p>The Palace of Westminster is the meeting place of the House of Commons and the House of Lords, the two houses of the Parliament of the United Kingdom. Commonly known as the Houses of Parliament after its tenants.</p>' +
'</div>']
];
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;
var infoWindow1 = [];
for( i = 0; i < farmerCropList.length; i++ ) {
var position = new google.maps.LatLng(farmerCropList[i].latitude, farmerCropList[i].longitude);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: farmerCropList[i].farmerCropId
});
infoWindow1[i] = new google.maps.InfoWindow({
content: '<div style="padding:5px;width:100%;height:auto;">' +
'<div style="padding:5px;width:400px;font-size:16px;text-align:left">Farmer Name : '+(farmerCropList[i].firstName + farmerCropList[i].lastName)+'</div>'+
'</div>'
});
var lastOpen = -1;
google.maps.event.addListener(marker, 'click', (function(marker, i) {
if (lastOpen > -1) {
infoWindow1[lastOpen].close();
}
return function(){
infoWindow1[i].open(map, marker);
}
lastOpen = i;
})(marker, i));
map.fitBounds(bounds);
}
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(15);
google.maps.event.removeListener(boundsListener);
});
google.maps.event.addDomListener(window, 'load', initialize);
}
You can use a KmlLayer
see this google developer sample
https://developers.google.com/maps/documentation/javascript/examples/layer-kml

info window not showing reverse geocoded address Google Maps V3

I'm coding a script that allows you to place a marker based on where you mouse click. I got that down. However, I cannot seem to get the infowindow to pop up when I pass in the reverse geocoded lat and lng. Could someone help me? Thanks!
Here is my code:
var geocoder;
function initialize()
{
geocoder = new google.maps.Geocoder();
var event = google.maps.event.addListener;
// intializing and creating the map.
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(-25.363882, 131.044922),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map'),
mapOptions);
event(map,'click',function(e){
var marker = placeMarker_and_attachMessage(e.latLng,map,count);
});
} // end of initalize.
/* place down marker based on where you click the mouse over a certain area on the map.
An infowindow should appear with the location of your marker.
*/
function placeMarker_and_attachMessage(position,map,num)
{
var event = google.maps.event.addListener;
var marker = new google.maps.Marker({
position: position,
map: map
});
var infowindow = new google.maps.InfoWindow({
content: info_text(position)
});
event(marker,'mouseover',function(){
infowindow.open(map,this);
});
event(marker,'mouseout',function(){
infowindow.close();
});
} // end of function.
// Takes in the position passed by the 'placeMarker_and_attachMessage' function and returns a human readable string
function info_text(position)
{
var location = position;
var latlngStr = location.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)
{
return results;
}
else
{
alert('could not pinpoint location');
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
In the code you posted, count is not defined in
var marker = placeMarker_and_attachMessage(e.latLng,map,count);

Getting The Name of Bus Stop in The Info Windows

Can you please help me to figure it out how to get the name of The Bus stop in a the info windows (or as a list) as following image?
I am using this example from Google Maps Api 3 examples and it is listing all Bus Stops but it just getting the title of the stops. Here is the code
var map;
var infowindow;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433, 151.1956316);
map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: 500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
This code is working but as I said it is just listing the Name of the stop:
Thanks for your comments a time