dsyph3r/google-geolocation-bundle
Installation:
deps file or Git submodules (as per README).app/autoload.php:
$loader->registerNamespaces([
'Buzz' => __DIR__.'/../vendor/Buzz/lib',
'Google' => __DIR__.'/../vendor/bundles',
]);
app/AppKernel.php:
new Google\GeolocationBundle\GoogleGeolocationBundle(),
Configuration:
app/config/config.yml:
google_geolocation:
api_key: "YOUR_API_KEY"
php app/console config:dump-reference Google\GeolocationBundle
First Use Case:
use Google\GeolocationBundle\Service\Geocoder;
class AddressController extends Controller
{
public function geocodeAction($address)
{
$geocoder = $this->get('google_geolocation.geocoder');
$result = $geocoder->geocode($address);
return $this->render('address/show.html.twig', ['result' => $result]);
}
}
Geocoding Addresses:
Geocoder service to convert human-readable addresses to coordinates:
$result = $geocoder->geocode('1600 Amphitheatre Parkway, Mountain View, CA');
$location = $result->getLocation();
$lat = $location->getLat();
$lng = $location->getLng();
Reverse Geocoding:
$result = $geocoder->reverseGeocode(37.422, -122.084);
$formattedAddress = $result->getFormattedAddress();
Batch Processing:
foreach ($addresses as $address) {
$geocode = $geocoder->geocode($address);
$address->latitude = $geocode->getLocation()->getLat();
$address->longitude = $geocode->getLocation()->getLng();
$address->save();
}
Caching Responses:
$cache = $this->get('cache');
$cacheKey = 'geocode_' . md5($address);
$result = $cache->get($cacheKey);
if (!$result) {
$result = $geocoder->geocode($address);
$cache->set($cacheKey, $result, 86400); // Cache for 1 day
}
Forms:
$builder->add('address', 'text');
$builder->add('latitude', 'hidden');
$builder->add('longitude', 'hidden');
$form->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
$data = $event->getData();
$address = $data['address'];
$geocoder = $this->get('google_geolocation.geocoder');
$result = $geocoder->geocode($address);
$data['latitude'] = $result->getLocation()->getLat();
$data['longitude'] = $result->getLocation()->getLng();
$event->setData($data);
});
APIs:
// src/YourBundle/Controller/GeocodeController.php
class GeocodeController extends Controller
{
public function geocodeAction(Request $request)
{
$address = $request->request->get('address');
$result = $this->get('google_geolocation.geocoder')->geocode($address);
return new JsonResponse($result->toArray());
}
}
Twig Integration:
{% for result in results %}
<p>{{ result.formatted_address }}</p>
<p>Lat: {{ result.location.lat }}, Lng: {{ result.location.lng }}</p>
{% endfor %}
API Key Management:
config.yml is insecure. Use environment variables or Symfony’s parameter bag:
# app/config/parameters.yml
google_api_key: "%env(GOOGLE_API_KEY)%"
parameters.yml to version control.Rate Limits:
try {
$result = $geocoder->geocode($address);
} catch (\Google\GeolocationBundle\Exception\GeocodingException $e) {
$this->addFlash('error', 'Geocoding failed: ' . $e->getMessage());
}
Deprecated Buzz:
Symfony 2 vs. 3/4:
Timeouts:
# app/config/config.yml
google_geolocation:
api_key: "%google_api_key%"
timeout: 10 # seconds
Enable Debugging:
$client = new Buzz\Client\Curl();
$client->setDebug(true); // Add this to the bundle's service configuration if possible.
Logging:
$logger = $this->get('logger');
$logger->info('Geocoding request', ['address' => $address, 'response' => $result->toArray()]);
Common Errors:
OVER_QUERY_LIMIT: You’ve exceeded Google’s usage limits. Implement caching or upgrade your plan.ZERO_RESULTS: The address couldn’t be geocoded. Validate input or handle gracefully:
if ($result->getStatus() === 'ZERO_RESULTS') {
$this->addFlash('warning', 'Address not found.');
}
Custom Response Handling:
Google\GeolocationBundle\Model\GeocodeResult class to add custom fields or logic:
class ExtendedGeocodeResult extends GeocodeResult
{
public function getDistance()
{
// Custom logic to calculate distance from a reference point.
}
}
Override Services:
Geocoder service with a custom implementation:
# app/config/services.yml
services:
your_bundle.geocoder:
class: Your\Bundle\Service\CustomGeocoder
arguments: ["@google_geolocation.geocoder"]
tags:
- { name: google_geolocation.geocoder }
Add New Features:
Testing:
Geocoder service in tests to avoid hitting the real API:
$mockGeocoder = $this->getMockBuilder('Google\GeolocationBundle\Service\Geocoder')
->disableOriginalConstructor()
->getMock();
$mockGeocoder->method('geocode')
->willReturn($mockResult);
$container->set('google_geolocation.geocoder', $mockGeocoder);
How can I help you explore Laravel packages today?