Getting coordinates based on city name google map - google-maps

I am trying to create coordinates based on city with google maps, here is example what i have for now, i always get error?
var address = 'Zurich, Ch';
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var Lat = results[0].geometry.location.lat();
var Lng = results[0].geometry.location.lng();
} else {
alert("Something got wrong " + status);
}
});
var myOptions = {
zoom: 11,
center: new google.maps.LatLng(Lat, Lng),
};

The geocoder is asynchronous. You need to use the returned data in the callback function when/where it is available.
related question: Using Address Instead Of Longitude And Latitude With Google Maps API
proof of concept fiddle
code snippet:
function initialize() {
var address = 'Zurich, Ch';
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var Lat = results[0].geometry.location.lat();
var Lng = results[0].geometry.location.lng();
var myOptions = {
zoom: 11,
center: new google.maps.LatLng(Lat, Lng)
};
var map = new google.maps.Map(
document.getElementById("map_canvas"), myOptions);
} else {
alert("Something got wrong " + status);
}
});
}
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"></script>
<div id="map_canvas"></div>

Related

Find the business name associated with a street address with the Google Maps API?

Using the Google Maps Platform (Web JavaScript API), how do I find the business name associated with a street address?
I would expect PlacesService.textSearch() or PlacesService.findPlaceFromQuery() to return both "street_address" and "establishment" types when querying by an address associated with a business/establishment. However, when I search by street address, I only receive "street_address" results.
For example, when searching "400 West Anderson Ln, Austin, Texas", I want to know that "Austin Parke Apartments" are at this address. How can I do that?
geocode the address
use the places library nearbySearch to find places near that address
pick the closest result
var address = "400 West Anderson Ln, Austin, Texas";
geocoder.geocode({
address: address
}, function(results, status) {
if (status === 'OK') {
map = new google.maps.Map(document.getElementById('map'), {
center: results[0].geometry.location,
zoom: 15
});
latLng = results[0].geometry.location;
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: marker.getPosition(),
rankBy: google.maps.places.RankBy.DISTANCE,
types: ["establishment"]
}, function(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var marker = createMarker(results[i], i);
if (i == 0)
google.maps.event.trigger(marker, 'click');
}
} else {
alert('nearbySearch was not successful for the following reason: ' + status);
}
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
})
proof of concept fiddle
code snippet:
var map;
var infowindow;
var latLng;
var address = "400 West Anderson Ln, Austin, Texas";
function initMap() {
infowindow = new google.maps.InfoWindow();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
address: address
}, function(results, status) {
if (status === 'OK') {
map = new google.maps.Map(document.getElementById('map'), {
center: results[0].geometry.location,
zoom: 15
});
latLng = results[0].geometry.location;
console.log(results[0].geometry.location.toUrlValue(6))
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: marker.getPosition(),
rankBy: google.maps.places.RankBy.DISTANCE,
types: ["establishment"]
}, function(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
console.log(results.length + " results returned");
for (var i = 0; i < results.length; i++) {
var marker = createMarker(results[i], i);
if (i == 0)
google.maps.event.trigger(marker, 'click');
else
marker.setMap(null);
}
} else {
alert('nearbySearch was not successful for the following reason: ' + status);
}
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
})
}
function createMarker(place, index) {
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 + "<br>" + address + "<br>" + index);
infowindow.open(map, this);
});
return marker;
}
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places,geometry&callback=initMap" async defer></script>

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>

Zooming and centering the geocoded place using google maps api

I am working with the google maps api for one of my application. I have a textbox in which the user enters place name. It should geocode the users place name given in the textbox and zoom and center to that geocoded place name. I am successful in the geocoding but zooming and centre is not as expected. The code and output snapshot is provided.The black rectangle in the image is the place name that was geocoded based on the user input in the textbox. But zooming and centering is somewhere in the corner of the map. I want it to make the geocoded place name in the center of map.
var mapProp = {
center: x,
zoom: 4,
disableDefaultUI: true,
mapTypeId: layer,
mapTypeControlOptions: {
mapTypeIds: [layer]
}
};
var map = new google.maps.Map(document.getElementById("googlemaps"), mapProp);
var geocoder = new google.maps.Geocoder();
var bounds = new google.maps.LatLngBounds();
map.mapTypes.set(layer, new google.maps.StamenMapType(layer));
geocoder.geocode({
'address': place_name_filter
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
map.fitBounds(results[0].geometry.viewport);
} else {
alert(place_name_filter + " not found");
console.log("status : ", status);
}
});
Place_name_filter is the variable which holds the the place name entered in the textbox.
Output_Snapshot_for_the_above_code
Expected_Output
To zoom to a result from the geocoder use map.fitBounds and the .geometry.viewport (or geometry.bounds) LatLngBounds in the response.
code snippet:
function initialize() {
var mapProp = {
center: {
lat: 25,
lng: -90
},
zoom: 4,
};
var map = new google.maps.Map(document.getElementById("googlemaps"), mapProp);
var geocoder = new google.maps.Geocoder();
var bounds = new google.maps.LatLngBounds();
var place_name_filter = "Abilene, TX";
geocoder.geocode({
'address': place_name_filter
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
map.fitBounds(results[0].geometry.viewport);
} else {
alert(place_name_filter + " not found");
console.log("status : ", status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#googlemaps {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="googlemaps"></div>

Google Maps API - Geocode & Search Nearby

I'm trying to merge together a GOOGLE geocoder script and a 'search nearby' script. I cannot seem to merge it successfully. Help?
The geocoder script lies here:
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);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
And the search nearby script lies here:
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'), {
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);
So I'm posting on here because I have no idea how to merge them. I tried to merge the scripts together but I couldn't get it to work. Any ideas?
Thanks.
Could be something like this sketch below.
Not sexy, but works.
Don't forget to include the places libary.
JS
var geocoder;
var map;
var infowindow;
var pyrmont = new google.maps.LatLng(-33.8665433, 151.1956316);
function initialize() {
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);
codeAddress();
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 codeAddress() {
geocoder = new google.maps.Geocoder();
var address = '100 Murray St, Pyrmont NSW, Australia';
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);
}
});
}
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);
http://jsfiddle.net/iambnz/c9ovns0o/
EDIT:
Or you can simply copy and paste this html file, this should work.
http://lab.sourcloud.com/stackoverflow/26071099/
EDIT 2:
First geocode the address and then show places nearby.
var geocoder;
var map;
var infowindow;
//var pyrmont = new google.maps.LatLng(-33.8665433, 151.1956316);
var nearbysearchloc = '';
function initialize() {
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);
codeAddress();
}
function codeAddress() {
geocoder = new google.maps.Geocoder();
var address = '100 Murray St, Pyrmont NSW, Australia';
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
});
ParseLocation(results[0].geometry.location);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
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);
});
}
function ParseLocation(location) {
var lat = location.lat().toString().substr(0, 12);
var lng = location.lng().toString().substr(0, 12);
nearbysearchloc = new google.maps.LatLng(lat, lng);
ShowPlacesAroundMe(nearbysearchloc);
}
function ShowPlacesAroundMe(location){
var request = {
location: location,
radius: 500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
google.maps.event.addDomListener(window, 'load', initialize);
http://jsfiddle.net/iambnz/c0omhyep/

Accessing longitude, latitude outside the geocode() function [duplicate]

This question already has answers here:
How do I return a variable from Google Maps JavaScript geocoder callback?
(5 answers)
Closed 7 years ago.
When I use the code below its alerting a blank value? why is that?
HTML
<body onload="initialize()">
<div id="map_canvas" style="width: 320px; height: 480px;"></div>
<div>
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Encode" onclick="display()">
</div>
</body>
JavaScript
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function codeAddress() {
var address = document.getElementById("address").value;
var loc=[];
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
loc[0]=results[0].geometry.location.lat();
loc[1]=results[0].geometry.location.lng();
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
return loc;
}
function display(){
var long_lat=codeAddress();
alert(long_lat);
}
because your function codeAddress is executed, assigning empty array to loc, executing asynchronous request to google geocoder and returns loc, which is empty, because its real value is assigned when response from google comes. In other words, allert should be inside response handler:
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function codeAddress() {
var address = document.getElementById("address").value;
var loc=[];
// next line creates asynchronous request
geocoder.geocode( { 'address': address}, function(results, status) {
// and this is function which processes response
if (status == google.maps.GeocoderStatus.OK) {
loc[0]=results[0].geometry.location.lat();
loc[1]=results[0].geometry.location.lng();
alert( loc ); // the place where loc contains geocoded coordinates
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
// pretty meaningless, because it always will be []
// this line is executed right after creating AJAX request, but not after its response comes
return loc;
}
function display(){
codeAddress();
}
this is how AJAX works... process results in callback handlers.
if you want to separate geocoding and 'dispalying' you can execute display function inside handler:
function codeAddress() {
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var loc=[]; // no need to define it in outer function now
loc[0]=results[0].geometry.location.lat();
loc[1]=results[0].geometry.location.lng();
display( loc );
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function display( long_lat ){
alert(long_lat);
}
html:
<input type="button" value="Encode" onclick="codeAddress()">
you can make it even more generic, if you will geocode not only to display. Then you can define callback as parameter to codeAddress function:
function codeAddress( callback ) {
...
geocoder.geocode( { 'address': address}, function(results, status) {
...
callback( loc ); // instead of dispaly( loc );
...
}
...
}
codeAddress( display ); // to execute geocoding