Search code examples
javascriptruby-on-railsgoogle-mapsgoogle-maps-api-3gmaps4rails

Gmaps4rails - how to set map language


I'd like to localise the map generated by Gmaps4rails, so I can show place names in the users desired language. Google documents how to do this here: https://developers.google.com/maps/documentation/javascript/examples/map-language

I'm using a fairly standard (and currently functional) implementation of Gmaps4rails, which you can see here.

handler = Gmaps.build('Google');
handler.buildMap({ 
    provider: { styles: mapStyle }, 
    internal: {id: 'map'}
}, function(){
    markers = handler.addMarkers(<%=raw @hash.to_json %>);
    handler.bounds.extendWith(markers);
    handler.fitMapToBounds();
});

Rendering to the html...

<div class="map-container">
  <div id="map"></div>
</div>

I just need to find out where to define the language code. I've tried adding it as an option to the provider, with no joy (e.g. provider: { styles: mapStyle, language: 'zh-TW' }).

I've scoured the documentation (and source), but can't seem to find any info on this. Any help would be appreciated!


Solution

  • You have to indicate the language in the script.

    For example in the Maps API v3 Now Speaks Your Language:

    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=pt-BR">
    

    You can find the list of languages here.

    Here is the code sample:

    <!DOCTYPE html>
    <html>
      <head>
        <title>Localizing the Map</title>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
        <meta charset="utf-8">
        <style>
          html, body {
            height: 100%;
            margin: 0;
            padding: 0;
          }
          #map {
            height: 100%;
          }
        </style>
      </head>
      <body>
        <div id="map"></div>
        <script>
          // This example displays a map with the language and region set
          // to Japan. These settings are specified in the HTML script element
          // when loading the Google Maps JavaScript API.
          // Setting the language shows the map in the language of your choice.
          // Setting the region biases the geocoding results to that region.
          function initMap() {
            var map = new google.maps.Map(document.getElementById('map'), {
              zoom: 8,
              center: {lat: 35.717, lng: 139.731}
            });
          }
        </script>
        <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&language=ja&region=JP"
        async defer>
        </script>
      </body>
    </html>
    

    As you can see in this code line, key=YOUR_API_KEY&callback=initMap&language=ja&region=JP, language is set to jp = Japanese.

    Also check their working sample with a dynamic language setting.

    Hope this helps!