arrow_back
Back

Google Maps JavaScript API: map, markers, circles, and geocoding

Andrew Dorokhov Andrew Dorokhov schedule 2 min read
menu_book Table of Contents

Documentation: open_in_new Maps Platform .

Init

<script async defer
  src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
<script>
function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {...});
}
</script>

Coordinates:

new google.maps.LatLng(40.770088, -73.971146);

Events: open_in_new Maps JavaScript API events .

Map

Every map needs at least center and zoom:

map = new google.maps.Map(document.getElementById('map'), {
  center: {lat: -34.397, lng: 150.644},
  zoom: 8
});

Map types

var mapOptions = {
  zoom: 8,
  center: myLatlng,
  mapTypeId: 'satellite'
};

Available types:

  • roadmap — default road map view;
  • satellite — Google Earth satellite imagery;
  • hybrid — mix of normal and satellite;
  • terrain — physical map based on terrain data.

Change dynamically:

map.setMapTypeId('terrain');

Marker

var marker = new google.maps.Marker({
    position: {lat: -25.344, lng: 131.036},
    map: map
});

Get position:

var coords = marker.getPosition();
var lat = marker.getPosition().lat();
var lng = marker.getPosition().lng();

With a custom icon:

new google.maps.Marker({
    position: event.latLng,
    icon: {
        url: window.app.iconRadiusCenter,
        anchor: {
            x: 25,
            y: 25
        }
    },
    map: map
});

Circle

var cityCircle = new google.maps.Circle({
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35,
    map: map,
    center: citymap[city].center,
    radius: Math.sqrt(citymap[city].population) * 100
});

Snippet: open_in_new markers inside a circle .

Geocoding (PHP)

Library: open_in_new geocoder-php/Geocoder .

HTTP adapters:

$http_client = new \Http\Adapter\Guzzle6\Client();
$http_client = new \Http\Client\Curl\Client();

Provider and query:

$http_client = new \Http\Adapter\Guzzle6\Client();

$provider = new \Geocoder\Provider\GoogleMaps\GoogleMaps($http_client, null, 'YOUR_API_KEY');

$result = $provider->geocodeQuery(GeocodeQuery::create('Buckingham Palace, London'));

var_dump($result->all());

Geocoding providers (pricing notes)

code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

Google Sheets API: auth, reading, writing, and spreadsheet metadata

arrow_forward