How to get current city name using google maps API (Laravel)
First of all we need to get a google maps API, go through this documentation to get an API of your own.
Place this script in your blade file if your are using Laravel or in your HTML inside body tags.
Make sure to put your API key in the place of YOUR_API_KEY in provided script above
Next thing you need to do after initializing the map is to create a method in jQuery for the call-back method initMap , it should match the the same callback in the script
After this first thing we need to do is to get our current location (let, long)
<button class="btn btn-success" onClick="getAddress()">Get Location</button>
What we have done in above js code
- getAddress method will get the current let long using geolocation that is provided by HTML;
- in the second function we are setting the value of two hidden input fields with the current let long;
- The initMap method will be called by our script that we initialized earlier
- The initMap method will call geocodeLatLng method to get the current let long from those hidden input
- Next thing we’re doing is splitting and formatting the let long value to provide it to geocoder
- you will get your current city name in this address variable
- Console Log the result variable and you’ll find more properties provide by geocode like long name, short name, postal code, area building number etc etc