Could not centralise the google map after location search in angular 2 - google-maps

I have a input field and a button. On click of button the location whatever written in the input field will set a marker in google map. I am able to locate a marker in map. But it wont appear in the centre. In fact map will stay constant whatever the location you search.
getAddress(place:Object) {
this.markers = [];
var address = this.step1Data.map_address;
if (!address) return false;
var geocoder = new google.maps.Geocoder();
var that = this;
geocoder.geocode({ 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var location = results[0].geometry.location;
var lat = location.lat();
var lng = location.lng();
that.markers.push({
lat: lat,
lng: lng,
label: 'A',
draggable: false
})
that._googleMapsApi.setCenter(location);
}
});
}
setCenter() method is not working here. May I know the reason. googleMapsApi is imported from angular2-google-maps/core.

Related

Google Maps API Geocode - return GPS coordinations [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I've got this code:
var get_lat = function(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log('lat is: '+ results[0].geometry.location.lat());
return results[0].geometry.location.lat();
}
});
}
var get_lng = function(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log('lng is: '+ results[0].geometry.location.lng());
return results[0].geometry.location.lng();
}
});
}
In console it prints the coordinates I need, but the return value is always undefined:
I use it in classic initialize for Google Maps like this:
function createMarker(latlng) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
});
}
function initialize() {
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(49.210366,15.989588)
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var address = "Correct address that console.logs the correct GPS coordinations in function definitions above";
var gps_lat = get_lat(address);
var gps_lng = get_lng(address);
console.log('GPS lat: ' + gps_lat); // logs "undefined"
console.log('GPS lng: ' + gps_lng); // logs "undefined"
var marker = createMarker({lat: gps_lat}, lng: gps_lng});
}
$(window).on("load", function (e) {
initialize();
});
Do you have any idea why the function consoles the right value but it doesn't return anything?
For GMAP API I use this script: http://maps.google.com/maps/api/js?sensor=false&libraries=geometry
You have the return inside an anonymous function that you pass to geocoder.geocode, all in yet another function (get_lat/get_lng). get_lat/get_lng themselves don't have a return statement, and thus return undefined.
Furthermore, geocoder.geocode will call your anonymous function asynchronously. Which means that there is no chance for get_lat/get_lng to get hold of the return value and return it where get_lat/get_lng was called.
One solution (the simplest one) is to put the createMarker code in the callback for geocoder.geocode. Also, in this case you will have to merge your two get_lat/get_lng functions. Example:
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var gps_lat = results[0].geometry.location.lat()
var gps_lng = results[0].geometry.location.lng();
console.log('lat is ' + gps_lat + '. lng is ' + gps_lng);
var marker = createMarker({lat: gps_lat, lng: gps_lng});
return results[0].geometry.location.lat();
}
});
You have to wait until Google API gives response. So write a logic to create marker in callback function of Google API as shown below.
var getLatLng = function (address)
{
geocoder.geocode({ 'address': address }, function (results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var location = results[0].geometry.location;
// Create marker once you get response from Google
createMarker({ lat: location.lat(), lng: location.lng() });
}
});
}
and call that function as shown below
function initialize()
{
var myOptions =
{
zoom: 8,
center: new google.maps.LatLng(49.210366, 15.989588)
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
var address = "Correct address that console.logs the correct GPS coordinations in function definitions above";
// Old code ------------------------------------------------
//var gps_lat = get_lat(address);
//var gps_lng = get_lng(address);
//console.log('GPS lat: ' + gps_lat); // logs "undefined"
//console.log('GPS lng: ' + gps_lng); // logs "undefined"
//var marker = createMarker({ lat: gps_lat, lng: gps_lng });
// ----------------------------------------------------------
// New code
getLatLng(address);
}
and you will get marker on a map

Convert lat,lng into Address and show on infoWindow google map api

I have list of lat, lng values in object
var path = [{"lat":"12.9247903824","lng":"77.5806503296"},{"lat":"10.9974470139","lng":"76.9459457397"}]
Here i have to convert latlng into address and have to show marker and infowindow. Address have to be shown in info window
I have tried this one, i have getting address and multiple markers but i not able to show address on info windows.. last infowindow only showing address
for (var i = 0; i < path.length; i++) {
var pos = new google.maps.LatLng(path[i]["lat"], path[i]["lng"]);
var marker = new google.maps.Marker({
position: pos,
map: map
});
geocoder.geocode({'latLng': pos}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
infowindow.setContent(results[i].formatted_address);
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
Do you have a listener to open the infowindow when you click a marker? Insert the geocoder function inside that listener, do the geocode, set content to the infowindow and then open the infowindow.

HTML5 - What is making this code get the country instead of city?

What is making the following code get the country and not the city, and how can I change it to get the city instead of country?
function get_visitor_country() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var latlng = new google.maps.LatLng(lat, lon);
geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var country = results[results.length-1].formatted_address;
$("#location-detection .location-name").html(country);
$("#geolocation-worked").css("display", "block");
$("#no-geolocation").css("display", "none");
$geolocation_fix.hide().css({ height : 0 });
init_geolocation_switch();
}
}
});
});
}
}
The script is also loading http://maps.google.com/maps/api/js?sensor=false at the end of the file, if that might be affecting it.
Your script currently is not getting anything special(like a city or a country) , it gets something out of the results.
To get the city search inside the results for an entry with types set to ["locality", "political"]
When you found it you got the city.
Creation of an object labeled with addressTypes for convenient access:
var components={};
jQuery.each(results,function(i,v){
components[jQuery.camelCase(v.types.join('-'))]=v;
})
//test it
alert((components.localityPolitical)
? components.localityPolitical.formatted_address
: 'n/a');
See: Address Component Types

Google Map API to detect user location

I am learning about jquery mobile. I came across a sample code which uses the following google maps api
http://maps.google.com/maps/api/js?sensor=false
And the code is to detect the current location of the user
function getPosition(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
//window.alert(results[1].address_components[0].long_name);
var locationVal = results[1].address_components[0].long_name;
var stateVal = results[1].address_components[1].short_name;
var location = document.getElementById('location');
location.value = locationVal;
}
}
});
}
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getPosition);
}
In the above code, in the results array, there is an address_components array. How to determine the properties of the results object and then again the properties of the address_component?
See here: http://code.google.com/apis/maps/documentation/javascript/geocoding.html

show postal code/zip code bounds on google map

I would like to mark the outline (bounds) of a postal code on a map. With google maps API, I can send a postal code or address and get back log/lat, then place a icon on a map. Now I would like to make a box or polygon around the entire area covered by the postal code. Is there an API or method to do this? I could use google maps or other service if available.
Api to get lat/lon of postal code...
if (geocoder) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK){
var pcode = results[0].address_components[0].long_name;
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
}
}
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var pcode = results[0].address_components[0].long_name;
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
//do whatever you want above then call the displayBounds function
displayBounds(results[0].geometry.bounds);
}
});
function displayBounds(bounds) {
var rectangleOptions = {
strokeColor: '#0000ff',
strokeOpacity: 0.5,
strokeWeight: 3,
bounds: bounds
}
var rectangle = new google.maps.Rectangle(rectangleOptions);
rectangle.setMap(map); //map being your google.maps.Map object
}
This way you can display the bounds on the map. Make sure you get the geometry.bounds on your results though, since it's not always the case.
DisplayZipCodeArea(results[0].geometry.bounds, resultsMap);
function DisplayZipCodeArea(bounds, resultsMap) {
var rectangleOptions = {
strokeColor: '#0000ff',
strokeOpacity: 0.5,
strokeWeight: 3,
bounds: bounds
}
var rectangle = new google.maps.Rectangle(rectangleOptions);
rectangle.setMap(resultsMap); //map being your google.maps.Map object
}