Git Product home page Git Product logo

datamaps's Introduction

⚠️ If you are interested in being added as a maintainer for Datamaps, please get in touch with me over email: mark dimarco at gmail

Datamaps

Join the chat at https://gitter.im/markmarkoh/datamaps

Interactive maps for data visualizations. Bundled into a single Javascript file.

Datamaps is intended to provide some data visualizations based on geographical data. It's SVG-based, can scale to any screen size, and includes everything inside of 1 script file. It heavily relies on the amazing D3.js library.

Out of the box it includes support for choropleths and bubble maps (see demos), but it's not limited to just that. Its new plugin system allows for the addition of any type of visualization over the map.

For feature requests, open an issue!

Downloads:

Documentation

Getting Started

  1. Include D3.js and Topojson on your page
  2. Include Datamaps.js on your page
  3. Add a container, set the height and width and position to relative
  4. Create a new Datamaps(options), passing in at least an element option

Example:

<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/topojson/1.6.9/topojson.min.js"></script>
<script src="/datamaps.world.min.js"></script>
<div id="container" style="position: relative; width: 500px; height: 300px;"></div>
<script>
    var map = new Datamap({element: document.getElementById('container')});
</script>

This should render a new world map with a standard projection.

via NPM

  1. npm install datamaps
  2. Refer to file in dist directory, like:
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/topojson/1.6.9/topojson.min.js"></script>
<script src="node_modules/datamaps/dist/datamaps.world.min.js"></script>
<div id="container" style="position: relative; width: 500px; height: 300px;"></div>
<script>
    var map = new Datamap({element: document.getElementById('container')});
</script>

via Bower

  1. bower install datamaps
  2. Refer to file in dist directory, like:
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/topojson/1.6.9/topojson.min.js"></script>
<script src="bower_components/datamaps/dist/datamaps.world.min.js"></script>
<div id="container" style="position: relative; width: 500px; height: 300px;"></div>
<script>
    var map = new Datamap({element: document.getElementById('container')});
</script>

USA Only Map

A map of the USA with an Albers based projection will be default if you only include datamaps.usa.min.js, but in case you include datamaps.all.min.js:

<script>
    var map = new Datamap({
        element: document.getElementById('container'),
        scope: 'usa'
    });
</script>

Changing the default fill colors

<script>
    var map = new Datamap({
        element: document.getElementById('container'),
        fills: {
            defaultFill: 'rgba(23,48,210,0.9)' // Any hex, color name or rgb/rgba value
        }
    });
</script>

Disabling popup or hover effects

<script>
    var map = new Datamap({
        element: document.getElementById('container'),
        geographyConfig: {
            highlightOnHover: false,
            popupOnHover: false
        }
    });
</script>

Using custom maps

<script>
    var map = new Datamap({
        element: document.getElementById('container'),
        geographyConfig: {
            dataUrl: '/custom.json'
        },
        scope: 'custom',
        setProjection: function(element, options) {
            var projection, path;
            projection = d3.geo.albersUsa()
                .center([long, lat])
                .scale(element.offsetWidth)
                .translate([element.offsetWidth / 2, element.offsetHeight / 2]);
}
            path = d3.geo.path()
                .projection( projection );

            return {path: path, projection: projection};
        }
    });
</script>

By specifying a dataUrl, Datamaps will attempt to fetch that resource as TopoJSON.

If you are using a custom map, you'll probably want to specify your own setProjection method as well.

setProjection takes 2 arguments, element as a DOM element, options as the original options you passed in. It should return an object with two properties: path as a d3.geo.path, projection as a d3.geo.projection

The example above will result in albersUsa projection.

custom UK based data

Read about other D3.js projections

Read more about TopoJSON

You can create any country's map using custom maps.

Follow the below steps:-

  1. Find the {xyz}.topo.json file for you country xyz. You can find from https://github.com/markmarkoh/datamaps/tree/master/dist.
  2. Extract Datamap.prototype.{xyz}Topo json and save it file named {xyz}.topo.json
  3. If the state codes contains dot(.) in the topo json, then you need to remove the dot from the code e.g, if your state code is CA.AL, remove CA. part to get 2-digit ISO code AL. If the states code are already in 2-digit ISO or do't have dot(.) then don't do any modification follow next steps.
  4. Objects country name in {xyz}.topo.json should be same as you declared in the Datamap scope. e.g, for Canada, in canada.topo.json we have {"type":"Topology","objects":{"can":{"type":"GeometryCollection"}}} and we have provided scope as 'canada' in the canada.html page. So this case 'can' in canada.topo.json must be as 'canada' i.e {"type":"Topology","objects":{"canada":{"type":"GeometryCollection"}}}.
  5. You need to override setProjection method, which is explained above three countires. You can refer any one.
  6. Done

Here are the some examples of different countries maps.

1. Bubble map on India Geographical region

india bubble map

india.html

 var bubble_map = new Datamap({
            element: document.getElementById('india'),
            scope: 'india',
            geographyConfig: {
                popupOnHover: true,
                highlightOnHover: true,
                borderColor: '#444',
                borderWidth: 0.5,
                dataUrl: 'https://rawgit.com/Anujarya300/bubble_maps/master/data/geography-data/india.topo.json'
                //dataJson: topoJsonData
            },
            fills: {
                'MAJOR': '#306596',
                'MEDIUM': '#0fa0fa',
                'MINOR': '#bada55',
                defaultFill: '#dddddd'
            },
            data: {
                'JH': { fillKey: 'MINOR' },
                'MH': { fillKey: 'MINOR' }
            },
            setProjection: function (element) {
                var projection = d3.geo.mercator()
                    .center([78.9629, 23.5937]) // always in [East Latitude, North Longitude]
                    .scale(1000);
                var path = d3.geo.path().projection(projection);
                return { path: path, projection: projection };
            }
});
Set the correct projection for India map on world map with the help of Longitude and Latitute of India (you can google it India Longitude and Latitute)

Please use india.toto.json for India geopraphy json data from https://github.com/Anujarya300/bubble_maps/blob/master/data/geography-data/india.topo.json, otherwise your map wont work. (I have truncated IND. from all state ISO code(2-digit ISO code), e.g IND.JH for Jharkhand state truncated to JH)  

Please note in setProjection method, I have set [78.9629, 23.5937] to locate center point for India in the world map. That means Latitude = 78.9629 E and Longitude = 23.5937 N. Remember Latitute and Longitude are always East and North. For western countries, Latitude are in West so make it convert as Negative of East. e.g 102.3421 W ==> -102.3421 E.

2. Bubble map on Canada Geographical region

canada bubble map

canada.html

var bubble_map = new Datamap({
            element: document.getElementById('canada'),
            scope: 'canada',
            geographyConfig: {
                popupOnHover: true,
                highlightOnHover: true,
                borderColor: '#444',
                borderWidth: 0.5,
                dataUrl: 'https://rawgit.com/Anujarya300/bubble_maps/master/data/geography-data/canada.topo.json'
                //dataJson: topoJsonData
            },
            fills: {
                'MAJOR': '#306596',
                'MEDIUM': '#0fa0fa',
                'MINOR': '#bada55',
                defaultFill: '#dddddd'
            },
            data: {
                'JH': { fillKey: 'MINOR' },
                'MH': { fillKey: 'MINOR' }
            },
            setProjection: function (element) {
                  var projection = d3.geo.mercator()
                .center([-106.3468, 68.1304]) // always in [East Latitude, North Longitude]
                .scale(250)
                .translate([element.offsetWidth / 2, element.offsetHeight / 2]);

                var path = d3.geo.path().projection(projection);
                return { path: path, projection: projection };
            }
        });
Set the correct projection for Canada map on world map with the help of Longitude and Latitute of Canada (you can google it Canada Longitude and Latitute)

Please use canada.toto.json for India geopraphy json data from https://github.com/Anujarya300/bubble_maps/blob/master/data/geography-data/canada.topo.json, otherwise your map wont work. (I have truncated CA. from all state ISO code(2-digit ISO code), e.g CA.TN to TN)

Please note in setProjection method, I have set [-106.3468, 68.1304] to locate center point for Canada in the world map. That means Latitude = 106.3468 W and Longitude = 68.1304 N. Remember Latitute and Longitude are always East and North. For western countries, Latitude are in West so make it convert as Negative of East. e.g 102.3421 W ==> -102.3421 E.

You can adjust this latitude and longitude co-ordinates by minor changing. e.g, if your map is not showing full view of North then you can change 68.1304 N to 70.3200 N or 71.3200 etc. if your map is not showing full view of East then you can change 32.1304 E to 70.3200 E or 30.3200 etc.

More about other countries maps

Creating a Choropleth

Probably the most common type of map visualization, where different states or countries are color coded. US election map, example of a choropleth

You'll need to know the 2 letter state code ('NY' for New York) or the 3 letter country code ('SCT' for Scotland) to fill in areas.

<script>
    var map = new Datamap({
        element: document.getElementById('container'),
        fills: {
            HIGH: '#afafaf',
            LOW: '#123456',
            MEDIUM: 'blue',
            UNKNOWN: 'rgb(0,0,0)',
            defaultFill: 'green'
        },
        data: {
            IRL: {
                fillKey: 'LOW',
                numberOfThings: 2002
            },
            USA: {
                fillKey: 'MEDIUM',
                numberOfThings: 10381
            }
        }
    });

    // Draw a legend for this map
    map.legend();
</script>

This will draw a world map and fill in IRL (Ireland) with the corresponding fills.LOW and USA with fills.MEDIUM.

You can also use fill: color for each state if you don't want to define a fillKey.

Colors will be applied in this order: fillKey, fill, defaultFill.

Updating a choropleth after initial drawing

map.updateChoropleth({
   USA: {fillKey: 'LOW'},
   CAN: '#0fa0fa'
});

You can specify either a literal color (as a string), or an object with a fillKey property.

Resetting a choropleth to defaultFill

The following will reset the entire map to the defaultFill and update CA to be filled green.

map.updateChoropleth({CA: 'green'}, {reset: true})

The following will reset the entire map to defaultFill

map.updateChoropleth(null, {reset: true})

The following will reset the entire map to defaultFill, but update the corresponding data of NY.

map.updateChoropleth({NY: {numberOfVoters: 55452}}, {reset: true})

You can also add a map legend with the legend plugin (used above)

Choropleth with auto-calculated color

Example highmaps_world.html explains how to create colorized map based on some quantity of things, Live Demo

Example result:

auto calculated color

Custom popup on hover

Expanding on the previous example of using data, any property passed into data will be sent to the popupTemplate function, which can be override to display custom messages.

<script>
    var map = new Datamap({
        element: document.getElementById('container'),
        fills: {
            HIGH: '#afafaf',
            LOW: '#123456',
            MEDIUM: 'blue',
            UNKNOWN: 'rgb(0,0,0)',
            defaultFill: 'green'
        },
        data: {
            IRL: {
                fillKey: 'LOW',
                numberOfThings: 2002
            },
            USA: {
                fillKey: 'MEDIUM',
                numberOfThings: 10381
            }
        },
        geographyConfig: {
            popupTemplate: function(geo, data) {
                return ['<div class="hoverinfo"><strong>',
                        'Number of things in ' + geo.properties.name,
                        ': ' + data.numberOfThings,
                        '</strong></div>'].join('');
            }
        }
    });
</script>

geographyConfig.popupTemplate, bubblesConfig.popupTemplate and arcConfig.popupTemplate just needs to return an HTML string, so feel free to use Handlebars or Underscore templates (instead of the terrible Array.join method above).

Bubbles

Bubbles in a core plugin that will render circles('bubbles') on different parts of the map. Each of these bubbles can be color coded in the same way a choropleth is color coded (see above 'Choropleth' example).

var bombMap = new Datamap({
    element: document.getElementById('map_bombs'),
    scope: 'world',
    geographyConfig: {
        popupOnHover: false,
        highlightOnHover: false
    },
    fills: {
        'USA': '#1f77b4',
        'RUS': '#9467bd',
        'PRK': '#ff7f0e',
        'PRC': '#2ca02c',
        'IND': '#e377c2',
        'GBR': '#8c564b',
        'FRA': '#d62728',
        'PAK': '#7f7f7f',
        defaultFill: '#EDDC4E'
    },
    data: {
        'RUS': {fillKey: 'RUS'},
        'PRK': {fillKey: 'PRK'},
        'PRC': {fillKey: 'PRC'},
        'IND': {fillKey: 'IND'},
        'GBR': {fillKey: 'GBR'},
        'FRA': {fillKey: 'FRA'},
        'PAK': {fillKey: 'PAK'},
        'USA': {fillKey: 'USA'}
    }
});

     var bombs = [{
        name: 'Joe 4',
        radius: 25,
        yield: 400,
        country: 'USSR',
        fillKey: 'RUS',
        significance: 'First fusion weapon test by the USSR (not "staged")',
        date: '1953-08-12',
        latitude: 50.07,
        longitude: 78.43
      },{
        name: 'RDS-37',
        radius: 40,
        yield: 1600,
        country: 'USSR',
        fillKey: 'RUS',
        significance: 'First "staged" thermonuclear weapon test by the USSR (deployable)',
        date: '1955-11-22',
        latitude: 50.07,
        longitude: 78.43

      },{
        name: 'Tsar Bomba',
        radius: 75,
        yield: 50000,
        country: 'USSR',
        fillKey: 'RUS',
        significance: 'Largest thermonuclear weapon ever tested—scaled down from its initial 100 Mt design by 50%',
        date: '1961-10-31',
        latitude: 73.482,
        longitude: 54.5854
      }
    ];
//draw bubbles for bombs
bombMap.bubbles(bombs, {
    popupTemplate: function (geo, data) {
            return ['<div class="hoverinfo">' +  data.name,
            '<br/>Payload: ' +  data.yield + ' kilotons',
            '<br/>Country: ' +  data.country + '',
            '<br/>Date: ' +  data.date + '',
            '</div>'].join('');
    }
});

bubble map

The first parameter to bubbles should be an array of objects, each with at least 3 properties:

  • latitude
  • longitude
  • radius

Optionally, pass in fillKey to color code the bubble, and pass in any other data you want to render in a popup template which can be overridden in the options parameter.

For further customization, you can set these properties on each bubble to override the options parameter (or default options):

  • borderColor
  • borderWidth
  • borderOpacity
  • fillOpacity

The second parameter is the options param, where you can override any of the default options (documented below)

Live updating of bubbles

You can continue to call bubbles on the same map instance and the map will auto update itself. Any bubble previously drawn that's not included in subsequent calls will be removed from the UI.

map.bubbles([]) will erase all bubbles.

Labels

For USA maps you can add 2 letter (i.e., NY, TX) labels to each state. To add labels, after created the map:

map.labels();

The following options are allowed:

  • labelColor // Font color, default: #000
  • lineWidth // Line width for New England states, default: 1
  • fontSize // Font size, default: 10
  • fontFamily // Font family, default: 'Verdana'
  • customLabelText // Replaces 2 letter labels with custom

An example for using the options:

map.labels({labelColor: 'blue', fontSize: 12});

An example for using the customLabelText

This accepts an object whose keys are uppercase 2 letter state codes. Values will be substituted for default label text Any missing values default to 2 state letters

newLabels = {'AK':'Alaska', 'AL':'123',.......};
map.labels({'customLabelText': newLabels});

Example custom-labels.html for using the customLabelText

custom labels

Zooming

You can override the default projection by setting your own setProjection(element) function. Example here

var map = new Datamap({
  scope: 'world',
  element: document.getElementById('container1'),
  setProjection: function(element) {
    var projection = d3.geo.equirectangular()
      .center([19, -3])
      .rotate([4.4, 0])
      .scale(400)
      .translate([element.offsetWidth / 2, element.offsetHeight / 2]);
    var path = d3.geo.path()
      .projection(projection);

    return {path: path, projection: projection};
  },

Using with jQuery

If jQuery is present on the page when the Datamaps library loads, it'll automatically create a jQuery plugin called datamaps that can be used like:

    <script>
        $("#container").datamaps(options);
    </script>

Events

All events are bubbled up to the root svg element and to listen to events, use the done callback.

<script>
    var map = new Datamap({
        element: document.getElementById('container'),
        done: function(datamap) {
            datamap.svg.selectAll('.datamaps-subunit').on('click', function(geography) {
                alert(geography.properties.name);
            });
        }
    });
</script>

Responsive Maps

Set responsive to true and then listen for resize events on window, and call Datamaps.prototype.resize.

Avoid setting the height and width of the container with hard pixel values, instead use percent values. (use 50% instead of 500px.

If the aspect ratio of your custom map is not the default 16:9 (0.5625), you should use the aspectRatio option to set it appropriately (eg. 0.3 for a 3:1 aspect ratio).

<div id="container"></div>
<script>
    var map = new Datamap({
        element: document.getElementById('container'),
        responsive: true
    });

    // Pure JavaScript
    window.addEventListener('resize', function() {
        map.resize();
    });

    // Alternatively with d3
    d3.select(window).on('resize', function() {
        map.resize();
    });

    // Alternatively with jQuery
    $(window).on('resize', function() {
       map.resize();
    });
</script>

Default Options

  {
    scope: 'world', // Currently supports 'usa' and 'world', however with custom map data you can specify your own
    setProjection: setProjection, // Returns a d3 path and projection functions
    projection: 'equirectangular', // Style of projection to be used. try "mercator"
    height: null, // If not null, datamaps will grab the height of 'element'
    width: null, // If not null, datamaps will grab the width of 'element',
    responsive: false, // If true, call `resize()` on the map object when it should adjust it's size
    done: function() {}, // Callback when the map is done drawing
    fills: {
      defaultFill: '#ABDDA4' // The keys in this object map to the "fillKey" of [data] or [bubbles]
    },
    dataType: 'json', // For use with dataUrl, currently 'json' or 'csv'. CSV should have an `id` column
    dataUrl: null, // If not null, datamaps will attempt to fetch this based on dataType ( default: json )
    geographyConfig: {
        dataUrl: null, // If not null, datamaps will fetch the map JSON (currently only supports topojson)
        hideAntarctica: true,
        hideHawaiiAndAlaska : false,
        borderWidth: 1,
        borderOpacity: 1,
        borderColor: '#FDFDFD',
        popupTemplate: function(geography, data) { // This function should just return a string
          return '&lt;div class="hoverinfo"&gt;&lt;strong&gt;' + geography.properties.name + '&lt;/strong&gt;&lt;/div&gt;';
        },
        popupOnHover: true, // True to show the popup while hovering
        highlightOnHover: true,
        highlightFillColor: '#FC8D59',
        highlightBorderColor: 'rgba(250, 15, 160, 0.2)',
        highlightBorderWidth: 2,
        highlightBorderOpacity: 1
    },
    bubblesConfig: {
        borderWidth: 2,
        borderOpacity: 1,
        borderColor: '#FFFFFF',
        popupOnHover: true, // True to show the popup while hovering
        radius: null,
        popupTemplate: function(geography, data) { // This function should just return a string
          return '<div class="hoverinfo"><strong>' + data.name + '</strong></div>';
        },
        fillOpacity: 0.75,
        animate: true,
        highlightOnHover: true,
        highlightFillColor: '#FC8D59',
        highlightBorderColor: 'rgba(250, 15, 160, 0.2)',
        highlightBorderWidth: 2,
        highlightBorderOpacity: 1,
        highlightFillOpacity: 0.85,
        exitDelay: 100, // Milliseconds
        key: JSON.stringify
    },
    arcConfig: {
      strokeColor: '#DD1C77',
      strokeWidth: 1,
      arcSharpness: 1,
      animationSpeed: 600, // Milliseconds
      popupOnHover: false, // True to show the popup while hovering
      popupTemplate: function(geography, data) { // This function should just return a string
        // Case with latitude and longitude
        if ( ( data.origin && data.destination ) && data.origin.latitude && data.origin.longitude && data.destination.latitude && data.destination.longitude ) {
          return '<div class="hoverinfo"><strong>Arc</strong><br>Origin: ' + JSON.stringify(data.origin) + '<br>Destination: ' + JSON.stringify(data.destination) + '</div>';
        }
        // Case with only country name
        else if ( data.origin && data.destination ) {
          return '<div class="hoverinfo"><strong>Arc</strong><br>' + data.origin + ' -> ' + data.destination + '</div>';
        }
        // Missing information
        else {
          return '';
        }
      }
    }
  }

#Contributing Guidelines

  • Do not run the grunt build task or submit any built files in your PR.
  • Have an example in src/examples if adding a new feature. Copy an existing feature .html file to start.

datamaps's People

Contributors

adrianbj avatar blackwatertepes avatar climbsrocks avatar enricoberti avatar etburke avatar gitter-badger avatar jasonkaz avatar jodonnell avatar justmarkup avatar keeganlow avatar kmarekspartz avatar liamgallivan avatar lulzia avatar madwort avatar magic890 avatar markmarkoh avatar matt-bernhardt avatar ramnathv avatar rmp avatar ronaldbradford avatar sam-kleiner avatar shailendher avatar smirecki avatar tbender85 avatar thebenedict avatar tmoitie avatar wesww avatar whroman avatar yeco avatar zeelux avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

datamaps's Issues

map doesn't show!

Hello !

Great job!
Exactly what I needed, easy customization and nice render.
I was very satisfied until... don't understand how... map disappeared...
No error, just an empty #container1...
I'm close to go back search another solution. Sadly...
Maybe u can 'throw an eye' on my page in case i missed something evident?

Thx for answer, I will send you the address by mail if you agree

regards,

rE

D3 Hexbin Plugin

I am working on a hexbin plugin for datamaps. Here is my work so far. It is still work-in-progress, but I thought I would share it with you to see if you had any early comments/feedback. Once, the plugin is complete, I will submit a pull request, if you think this would be an interesting feature for datamaps.

Not working on IE

Hi again, I have been playing a lot with the plugin and it works great on Firefox and Chrome but not on IE (all versions).. when I mouseover a region on the map the region disappears.. any idea? is not supported on IE?

Thanks!

Can't find variable Datamap

I'm very new to D3 and relatives (as well as Javascript), so bear with me...

Using the following imports in the head block of my html:

<script src="http://d3js.org/d3.v3.min.js" type="text/javascript"></script>
<script src="http://d3js.org/topojson.v1.min.js" type="text/javascript"></script>
<script src="http://datamaps.github.com/scripts/datamaps-all.js"></script>

I cannot seem to create a Datamap object using new Datamap. I'm however successful using new Map. In this case though I have to substitute the element key for el and geographyConfig for geography_config etc. Thus I suspect something is very wrong in how I import Datamaps, but I can't seem to figure it out - Any suggestions would be very welcome...

best

Thomas

Slight redesign of Legend possible?

Now the legend is displayed like this: 1-12 ▒ 13-450 ▓

Would it be possible to have this:
1-12 ┈ 13-450
┈ ▒ ┈┈ ▓
so that the color boxes and the labels are in two rows rather than in one?

An issue with the current design is that if you limit the width in which the legend is shown (to display the legend vertically instead of horizontally) you end up with something like this:
1-12 ▒
13-450 ▓
the color boxes are not aligned horizontally.

(A quick fix might be to swap the color boxed and the text label. i.e.: ▒ 1-12 ▓ 13-450 . That way the color boxes are always vertically aligned if you limit the width like before.
It would be:
▒ 1-12
▓ 13-450 )

Thank you for the great datamaps!

Passing Data as Argument to done method

Is it possible to access the data associated with an element when using the done method to trigger an action. I see that geography is allowed, but wasn't able to get data working, just like in popupTemplate.

Issues loading dependencies with RequireJS

Hey, I noticed that when trying to include datamaps in some sort of AMD pattern, there is an error triggered that I can't seem to figure out

Here is a picture of the network requests showing that all libraries are loading in the intended order:

screen shot 2014-02-04 at 4 42 19 pm

And here is my RequireJS settings:

app.js:

requirejs.config({
  'baseUrl': 'js/lib',
  'paths': {
    'app': '../app',
    'jquery': 'jquery',
    'd3': 'd3',
    'topojson': 'topojson',
    'domReady': 'domReady',
    'datamaps': 'datamaps'
  },
  shim: {
    d3: {
      exports: 'd3'
    },
    topojson: {
      deps: ['d3'],
      exports: 'topojson'
    },
    datamaps: {
      deps: ['d3', 'topojson']
    }
  }

});

/** Load main module to start app **/
requirejs(["app/main"]);


And here is the main app that is being run:

main.js:

define(function(require) {
  var $ = require('jquery');
  var d3 = require('d3');
  var topojson = require('topojson');
  var domReady = require('domReady');
  var Datamap = require('datamaps');

  domReady(function() {
    // Begin drawing for SVG map
   var map = new Datamap({element: $('#container')[0]});
    });

});

And here is the HTML:

<html>
  <head>
    <script data-main="js/app" src="js/lib/require.js"></script>
  </head>
  <body>
    <h1>Testing</h1>
    <p>Testing the page</p>
    <div id="container" style="position: relative; width: 500px; height: 300px;"></div>
  </body>
</html>

Every time it runs though I get the error:

Uncaught Error: Include d3.js (v3.0.3 or greater) and topojson on this page before creating a new map 

This is what happens when I add the lines:

console.log(d3);
console.log(topojson);

to main.js:

define(function(require) {
  var $ = require('jquery');
  var d3 = require('d3');
  var topojson = require('topojson');
  var domReady = require('domReady');
  var Datamap = require('datamaps');

  domReady(function() {
    // Begin drawing for SVG map
   console.log(d3);
   console.log(topojson);
   var map = new Datamap();
    });

});

which gives the result as follows:
screen shot 2014-02-04 at 4 52 59 pm

Any ideas of what could be going wrong?

both d3 and topojson are clearly being loaded, been having a heart attack trying to work this out haha

Animate bubble remove after new data gets loaded

When we update new data on .bubbles([]) all the previous bubble disappears immediately. Can we make the bubble remain there for some time and then remove them from the map using jquery animation and also display a new bubbles at certain time periods?

add lat and long lines?

hey Mark,

DataMaps is awesome, thanks so much for building. Was looking to either add or bring back latitude and longitude lines that Mike Bostock usually includes with d3.geo http://bl.ocks.org/mbostock/3682698 -- was looking for a way to add them in datamaps.all.js but just kept breaking things. Is this an easy addition?

let me know, thanks!

Fillkey alias

Hi, is there any way to rename or assign an alias name to the "fillKey"? I'm creating a table based on the data shown in the map but I don't want to display the header as "fillkey"

Thanks always for your help and support!

US with PR and VI

I'm trying to map a companies locations and was wondering if it is it possible to have a US map that also displays Puerto Rico and the US Virgin Islands? I thought this might be the listing on the main page saying a build is available for "USA & Countries w/ dependencies" but I see no documentation on how to access this.

Bubbles Issue

Hi,

I've been following the examples on the main page, and can get them all working. However, if I modify the bubbles map to use: dataUrl: '/data/uk.topo.json' (and create some bubbles over the UK), the bubbles appear beneath the map. Is there any reason for this, and is there any way and can get them to appear above the map?

Thanks,

Ian

How to pass custom legend labels?

I'm looking over the source code for the legend, and am trying to understand how custom label text should be specified. I've been able to set the legend title, and the default label, using

map.legend({
    legendTitle : "Total Downloads",
    defaultFillName: "No data",
})

However, the example that ronaldbradford gives in #39 isn't working? Here is how I'm calling the map

  var map = new Datamap({
    element: document.getElementById('map'),
    geographyConfig: {
      popupTemplate: function(geography, data) {
        return '<div class="hoverinfo"><strong>' + geography.properties.name + '<br>' + data.downloads.toLocaleString() + '</strong></div>';
      }
    },
    fills: {
      defaultFill: "#cccccc",
      q0: "rgb(242,242,242)",
      q1: "rgb(173,186,206)",
      q2: "rgb(132,152,181)",
      q3: "rgb(90,117,156)",
      q4: "rgb(49,83,132)",
      q5: "rgb(8,48,107)",
    },
    data: mapdata
  });

  map.legend({
    legendTitle : "Total Downloads",
    defaultFillName: "No data",
    labels: {
      q0: "one",
      q1: "two",
      q2: "three",
      q3: "four",
      q4: "five",
      q5: "six,"
    },
  });

Any pointers would be appreciated -

How to update an already created DataMap

A simple example would be where users can choose a color palette for the choropleth map. How can I modify the configuration for a datamap that has already been drawn?

update data

Hi, to put it in another way:
how could I easily update the map's data?

IE 7 & IE 8

Hi all,
Is there any way that I could get it to work for IE 7 & IE 8.
Thanks :)

Help with D3.js maps

I am new to the D3 mapping. I am trying to figure out how to set up a map for New York State and then show data either by county of congressional district.

Doesn't play nicely with NVD3 legend toggle

Unable to use the legend to toggle elements in an nvd3 chart if datamaps.js is loaded in the head of the doc. Seems to be intercepting the state change and shooting this error:

New State: {"disabled":[false,true]} nv.d3.min.js:1 Uncaught TypeError: Cannot read property '1' of undefined datamaps.js:21 xn.transition datamaps.js:21 (anonymous function) nv.d3.min.js:2 r datamaps.js:21 (anonymous function) nv.d3.min.js:2 u

To reproduce:

  1. Go to http://nvd3.org/livecode/
  2. Click "Line Plus Bar Chart" example.
  3. In Markup(HTML/CSS) tab, add <script src="https://raw.github.com/markmarkoh/datamaps/master/dist/datamaps.js" type="text/javascript"></script>
  4. Click "Quantity (left axis) in the legend at the top of the chart (or price)
  5. Error will show in console.
  6. Sob deeply. ;)

Bubble Settings

A second issue / question -- if using bubbles to mark locations, is there a way to offset if 2 markers occupy the same space (example; a company has different divisions each represented by a different color marker, but more than 1 division serves the same city. Currently the last one in the backbone collection is on top and the other is not seen.)

I would like to take out the possibility of user error in overlooking multiple locations and having to adjust LONG/LAT coordinates to display both.

datamaps as plugin

Great work.

Thought I'd ask, is it possible to include the datamaps.js file as a script in the latest d3.js (v3) examples, and then use the functionality that it provides? For instance, I have d3 rendering a geojson file and I would like to have datamaps colouring that map as a chloropeth. Is this possible at all? I have a feeling it isn't as yet as the datamaps library is tightly coupled to the data - hence world and usa.

bower.json main path not correct

I had to change to:
"main": "dist/datamaps.all.js"

Once I changed this line the library was loaded correctly with the bower-install grunt task.

Full example of custom maps

Hi,

I'm really struggling to follow your custom maps documentation. If you could include a fully working example of a custom map, that would be amazing.

Thanks

Live update of arcs (and bubbles)

Hi,

I can't get the live update of arcs to work. I want to change the color of the arcs based on some external data, but the arcs don't update when a call .arc (same with bubbles). I got it to work if I first call .arc with the new options, and then call map.arc([]) to clear all arcs, then the arcs show up with the new colors. Am I missing something?

Make it responsive

Hi, I'm trying to implement the map with bootstrap (to make it responsive) but without success so far, any idea?


<div class="container">
   <h2>Interactive Map</h2>
<div class="row">

<div class="span12">
<div id="container1">

</div>
</div>
</div>
</div>

Read in data from csv file?

The library is fantastic and I'm using it a lot right now! It would make my work much easier if it was possible to read the data from a .csv file. Did anybody try this before? What am I doing wrong?

I would build a jsfiddle but I don't know how to use a csv file in these IDEs. Sorry about that.

What I'm trying to do is the following:

The csv file looks like this:

ISO,Rate,fillKey
SLE,181.6,>100
HTI,75.6,50-100
ZAF,44.6,20-50
NPL,41.6,20-50
BOL,41.4,20-50

And then I'm trying to use the following:

var data;

d3.csv("data.csv", function (error, csv) {
  if (error) return console.log("error loading the csv: " + error);
  console.log("there are " + csv.length + " elements in my csv set");

  var nestFunction = d3.nest().key(function(d){return d.ISO;});

  data = nestFunction.entries(
                      csv.map(function(d){ 
                                     d.Rate = +d.Rate;  
                                     d.fillKey = d.fillKey;  
                                     return d;  
                                 })

                    ); 

  console.log("there are " + data.length + " elements in my data");

});


var myMap = new Datamap({
    element: document.getElementById('map'),
    scope: 'world',
    geographyConfig: {
        popupOnHover: false,
        highlightOnHover: false
    },
    fills: {
        '>100': '#1f77b4',
        '50-100': '#9467bd',
        '20-50': '#ff7f0e',
        defaultFill: '#EDDC4E'
    }
});

how to add a new country (singapore) attributes in the map?

Hi,

I know for a fact that I have to modify the world.js file to add new countries.
I am unable to figure out what the "arcs" attributes do? how to set attributes for a new country like singapore?

{
"type": "Polygon",
"id": "AFG",
"arcs": [
[0, 1, 2, 3, 4, 5]
],
"properties": {
"name": "Afghanistan"
}
}

Is it possible to have a custom map?

I want to add "Iran" to geoJSON,I wonder if there is a simple way to add countries to
this component, the js size will be too large if I add it by code.
thanks in advance

Arc global options are not used

    <script src="http://datamaps.github.io/scripts/datamaps.world.js"></script>
    […]
    var map = new Datamap({
        element: document.getElementById('container'),
        projection: 'mercator',
        geographyConfig: {
            popupOnHover: false,
            highlightOnHover: false
        },
        arcConfig: {
            strokeColor: '#000000',
            strokeWidth: 10
        }
    });

    map.arc([{
        origin: { latitude: 10, longitude: 20 },
        destination: { latitude: 50, longitude: 90 },
    }])

Arcs are not black and 10px width!

Enable customizable Legend Labels

When you add a legend, the fill names are used. I want to see custom labels in the legend.

var map = new Datamap({
  element: document.getElementById("map"),
  scope: 'world',
  projection: 'mercator',
  geographyConfig: {
    highlightOnHover: false,
    popupOnHover: true
  },
  fills: {
    you: "red",
    spouse: "green",
    together: "blue",
    separately: "yellow",
    defaultFill: "#EFEFEF",
  },
  data: world
});

var l = {
  legendTitle: "Where Have We Been",
  defaultFillName: "Whats left",
  labels: {
     you: "Fred",
     spouse: "Wilma",
     together: "Together",
     separately: "Separately",
  },
};
map.legend(l);

Is there a way to customize bubble color?

Bubble color appears to default to the fill color of the map tile. In the bubble data hash I've tried setting fillKey. fill, and fillColor in hopes of setting the bubble color. Is it even possible?

Responsive Maps and Continuous Legends

I am digging datamaps and find it to be the perfect solution to quickly generate choropleths and bubble maps. I came across this post on responsive maps with d3.js. Is it possible to adapt some of the ideas from this post to make the maps made with datamaps responsive?

IE 11 MouseOut

Datamaps Countries are reacting on Hover, but doesn't come back to original color on MouseOut.
Tested on IE 11.

Use ISO two letters countriy code

If you need as me to use ISO two letters county code, then replace the worldTopo line with that line:

Ooops: the text is too long, so if someone needed it, just replay with email, and I'll send. it

Custom Business Regions

Hi mate,
Impressive work. Could you please point out if there a sample that could help me with following scenario.
I have custom financial regions, Americas, EMEA and APAC. Within these regions I have custom regions for an e.g. Americas has South, East, West and central; APAC has Philippines, India, Australia and New Zealand. Within these sub-regions I have country/state and then individual stores within a country.
What i would like to do is to create one layout for each main region, so when plotting out the Americas, it should not plot the US and Canada with in it - just one region.
Hope I am making sense.
Thanks for your help :)

Update on resize

Any plans to allow the map to redraw automatically when the browser is resized?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.