Smashinglabs

Sebastian Poręba's blog

Simple map with marker

Displays a simple map with controls and adds one marker. The viewport gets centered automatically.
    

$("#map0_1").gMap({
markers: [{ latitude: 50.083, longitude: 19.917 }]
});
    
Loading...

Different map type

Changes the map type to physical view.

Please note: Available since version 1.0.1
Please note 2: Passed argument has changed in V3 API. Read more here.
    

$("#map0_2").gMap({
markers: [{ latitude: 50.083, longitude: 19.917 }]
maptype: google.maps.MapTypeId.TERRAIN
});
    
Loading...

Controls and map center

Every type of control has its own boolean flag. Usually default setting is just fine.
I recommend setting latitude and longitude of map center and zoom level for performance reasons.
    
$("#map0_3").gMap({
    mapTypeControl:         false,
    zoomControl:            false,
    panControl:             false,
    scaleControl:           false,
    streetViewControl:      false,

    scrollwheel: false,

    latitude: 50.083,
    longitude: 19.917,
    zoom: 10
});
    

Loading...

Map with marker and info window

Same as example above but with info window that pops up and title.
        
$("#map1_1").gMap({
    markers: [
        {
            latitude: 50.083,
            longitude: 19.917,
            html: 'Kraków, Polska',
            title: "Kraków",
            popup: true
        }
    ],
    zoom: 6
});
        
    
Loading...

Addresses (geocoding) and references

Since version 1.1.0 you can use addresses instead of latitude/longitude.

gMap automatically geocodes the given string and places a marker or even center the viewport.
You can set the html-property of a marker to "_address" or "_latlng" to display the address or latitude/longitude.
        

$("#map1_2").gMap({
    markers: [
        {
            latitude: 50.083,
            longitude: 19.917,
            html: '_latlng'
        },
        {
            address: 'Rynek Główny, Kraków, Poland',
            html: 'Rynek Główny in Cracow'
        },
        {
            address: 'Wieliczka, Poland',
            html: '_address'
        }
    ],
    address: 'Kraków, Poland',
    zoom: 10
});
        
    
Loading...

Extended usage

Map without controls, custom marker images, multiple markers, custom viewport position and zoom.
        
$("#map1_3").gMap({
    mapTypeControl:         false,
    zoomControl:            false,
    panControl:             false,
    scaleControl:           false,
    streetViewControl:      false,

    scrollwheel: false,
    markers: [
        {
            latitude: 50.083,
            longitude: 19.917,
            icon: {
                image: '/images/gmap_pin_orange.png',
                iconsize: [26, 46],
                iconanchor: [12,46],
                infowindowanchor: [12, 0]
            }
        },
        {
            latitude: 50.20917,
            longitude: 19.75435,
        },
        {
            latitude: 50.502343,
            longitude: 19.91243,
            icon: {
                image: '/images/gmap_pin_grey.png',
                iconsize: [26, 46],
                iconanchor: [12,46],
                infowindowanchor: [12, 0]
            }
        }
    ],
    icon: {
        image: '/images/gmap_pin.png',
        iconsize: [26, 46],
        iconanchor: [12, 46],
        infowindowanchor: [12, 0]
    },
    latitude: 50.083,
    longitude: 19.917,
    zoom: 10
});
            
        
Loading...

Callbacks

Sometimes you want to manage your markers after initial load. I rebuilt gMap from scratch to support for-later-usage functions.
Below, you can see that marker is added with no popup settings. I add them later, using jQuery .data() function (click on marker to check).
        
$("#map2_1").gMap({
    markers: [{ latitude: 50.083, longitude: 19.917 }],
    zoom: 10,
    //this way we ensure, that markers are already added
    onComplete: function() {
        var data = $('#map2_1').data('gmap');
        var infowindow = new google.maps.InfoWindow({
            content: "my awesome content"
        });
        google.maps.event.addListener(data.markers[0], 'click', function() {
            infowindow.open(data.gmap, data.markers[0]);
        });
    }
});
        
    
Loading...

Example: calculate route between two markers

Here is a little more complex example of what can be achieved using new 3.1.0 features.
Notice text below the map, it's loaded when path is found. Reload page to see placeholder (if you have fast connection, you won't see any).
There is a little performance issue in code below - markers are first geolocated and retrieved LatLngs are passed to directionsService.
You can set address string directly as origin and destination if you want, you don't need these markers anyway.
        
$("#map2_2").gMap({
    markers: [
        { address: "Rynek Główny, Kraków, Poland" },
        { latitude: 52.2296756, longitude: 21.0122287 }
    ],
    latitude: 51.919438,
    longitude: 19.145136,
    zoom: 6,
    onComplete: function() {
        var data = $('#map2_2').data('gmap'),
            directionsService = new google.maps.DirectionsService(),
            directionsDisplay = new google.maps.DirectionsRenderer();
        directionsDisplay.setMap(data.gmap);
        // disable A/B markers
        directionsDisplay.setOptions({suppressMarkers: true});

        var path = {
          origin: data.markers[0].getPosition(),
          destination: data.markers[1].getPosition(),
          provideRouteAlternatives: false,
          travelMode: google.maps.DirectionsTravelMode.DRIVING,
          unitSystem: google.maps.DirectionsUnitSystem.METRIC
        };

        directionsService.route(path, function(result, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                //remove default markers
                data.markers[0].setMap(null);
                data.markers[1].setMap(null);

                directionsDisplay.setDirections(result);
                $("#map2_2_result").html(result.routes[0].legs[0].distance.text + " using " + result.routes[0].summary);
            }
        });
    }
});
        
    
Loading...

Result of route finding will be loaded here, please wait. If you see this text for a long time, something went wrong, sorry.

Example: loading new markers with ajax request

Creating fully AJAX featured website often requires reloading markers on map - for example, if you want to add dynamic search feature.
Below you can see example of markers loaded with jQuery.getJSON request. These are totally random, but you can easily modify it and add some DB rows fetching.
        

var map2_3 = $("#map2_3");
map2_3.gMap({
    latitude: 51.919438,
    longitude: 19.145136,
    zoom: 6
});

$('#map2_3_newMarkers').click(function(e) {
    $.getJSON('/examples/randomMarkers.php?callback=?',
        function(data){
            var i;
            map2_3.gMap('removeAllMarkers');
            for(i = 0; i < data.markers.length; i += 1) {
                map2_3.gMap('addMarker', data.markers[i]);
            }
        }
    );
    e.preventDefault();
});
        
    
Load new random markers
Loading...
I hear a lot of complaints about gMap loading issues. It is not only gMap problem, so even if you use pure Google Maps API, keep reading, you may find this section useful.
Google Maps are based on size of div in which they are loaded. If, for any reason, any dimension of div will be equal 0 during loading process, maps will stop working correctly. It is quite common issue while loading tabs, accordions, etc. Also "show map" buttons keep annoying people. Google Map treat invisible div as width = 0, height = 0. Also it will not detect div resizing.
Here I provide few simple solutions for various methods: If solution you are looking for is not there, and above examples are still not helping you (which I hardly believe), you can try these generic tips:
  • Always try to load map after tab/accordion/whatever is already shown. Most JS frameworks and plugins provide onComplete callback methods - make use of them.
  • If you can't use callback, you have to trigger resize event manually by calling: google.maps.event.trigger($('#map').data('gmap').gmap, 'resize');
  • If you had to trigger resize manually, you may have to move map center to the correct point. There are two ways to do it, both explained in jQuery .show() example.
  • With panBy() and panTo(), if the change is less than both the width and height of the map, the transition will be smoothly animated. I use hack to avoid this default behaviour - I move panTo(new google.maps.LatLng(0,0)) and then to the correct center.
  • Always trigger resize event before using panTo(). With panBy() it is not necessary.
  • Do not reload gMap on every tab/accordion/whatever activation, only on first one. Again, check one of the examples to see how.
  • RSS
  • Facebook
  • Twitter

FAQ about Wordpress

This came as a surprise for me but gMap is ...

gMap 3.3.3 released

It was a looong time since I last visited gMap. ...

Talks for Google Dev

Two new slide decks appeared in lectures tab. This time with ...

Talks and lectures w

Every now and then I spend a weekend watching various ...

3D Tetris with Three

In the fifth part of tutorial we add some final ...

FAQ about Wordpress

This came as a surprise for me but gMap is ...

gMap 3.3.0 released

Christmas came early! New version of gMap is ready!

Lecture for GTUG: Ja

Today I gave a lecture for GTUG Krakow about optimizations in ...

Unit testing for jQu

In part 1 I described basics of unit testing in ...

Unit testing for jQu

In part 1 I described some basic concepts behind unit ...