Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <!DOCTYPE html>
<html>
<head>
  <title>City Map with Circular Marks and Shop Sales</title>
  <script src="https://d3js.org/d3.v6.min.js"></script>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
    }

    #map {
      width: 100%;
      height: 100vh;
    }

    .tooltip {
      position: absolute;
      background-color: rgba(0, 0, 0, 0.8);
      color: #fff;
      padding: 5px;
      font-size: 12px;
      pointer-events: none;
    }

    #chart {
      position: fixed;
      bottom: 20px;
      right: 20px;
      width: 300px;
      height: 200px;
      background-color: #f5f5f5;
      border: 1px solid #ccc;
      padding: 10px;
    }

    .chart-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 10px;
    }

    .chart-bar {
      fill: steelblue;
    }

    .chart-bar.highlight {
      fill: orange;
    }

    .chart-axis path,
    .chart-axis line {
      fill: none;
      stroke: #999;
      shape-rendering: crispEdges;
    }

    .chart-axis .tick text {
      font-size: 10px;
    }
  </style>
</head>
<body>
  <div id="map"></div>
  <div id="chart">
    <div class="chart-title">Shop Sales</div>
    <svg class="chart-svg"></svg>
  </div>

  <script>
    const data = [
      {
        city: 'New York',
        shops: [
          { name: 'Fashion World', sales: 3800 },
          { name: 'Super Grocery', sales: 7200 }
        ],
        lat: 40.7128,
        lon: -74.0060
      },
      {
        city: 'Los Angeles',
        shops: [
          { name: 'Outdoor Gear', sales: 6500 },
          { name: 'Fashion Trends', sales: 4900 },
          { name: 'Health Emporium', sales: 3900 }
        ],
        lat: 34.0522,
        lon: -118.2437
      },{
    city: 'Colorado Springs',
    shops: [
      { name: 'Tech Zone', sales: 5700 },
      { name: 'Fashion Trends', sales: 4400 },
      { name: 'Organic Market', sales: 4000 }
    ],
    lat: 38.8339,
    lon: -104.8214
  },
  {
    city: 'Virginia Beach',
    shops: [
      { name: 'Gadget World', sales: 5200 },
      { name: 'Urban Style', sales: 4900 },
      { name: 'Health Hub', sales: 5100 }
    ],
    lat: 36.8529,
    lon: -75.9780
  },
  {
    city: 'Raleigh',
    shops: [
      { name: 'Fitness Pro', sales: 3900 },
      { name: 'Home Essentials', sales: 4500 },
      { name: 'Books and More', sales: 4700 }
    ],
    lat: 35.7796,
    lon: -78.6382
  },
  {
    city: 'Omaha',
    shops: [
      { name: 'Fashion Lane', sales: 5100 },
      { name: 'Super Mart', sales: 4700 },
      { name: 'Tech Zone', sales: 4300 }
    ],
    lat: 41.2565,
    lon: -95.9345
  },
      // Add more cities and shops with sales here...
    ];

    const svg = d3.select('#map')
      .append('svg')
      .attr('width', '100%')
      .attr('height', '100%');

    // Projection for converting latitude and longitude to coordinates
    const projection = d3.geoNaturalEarth1().scale(150).translate([window.innerWidth / 2, window.innerHeight / 2]);

    // Path generator for drawing map paths
    const path = d3.geoPath().projection(projection);

    // Create a tooltip for displaying shop information
    const tooltip = d3.select('body')
      .append('div')
      .attr('class', 'tooltip')
      .style('opacity', 0);

    // Create the bar chart container
    const chartContainer = d3.select('#chart');

    // Draw the bar chart with sales data
    function drawBarChart(cityData) {
      chartContainer.select('.chart-svg').html(''); // Clear the previous chart

      const shopsData = cityData.shops;

      const chartWidth = 280;
      const chartHeight = 180;
      const padding = 40;

      const xScale = d3
        .scaleBand()
        .domain(shopsData.map((d) => d.name))
        .range([padding, chartWidth - padding])
        .paddingInner(0.2)
        .paddingOuter(0.2);

      const yScale = d3
        .scaleLinear()
        .domain([0, d3.max(shopsData, (d) => d.sales)])
        .range([chartHeight - padding, padding]);

      const xAxis = d3.axisBottom(xScale);
      const yAxis = d3.axisLeft(yScale);

      const chart = chartContainer.select('.chart-svg')
        .attr('width', chartWidth)
        .attr('height', chartHeight);

      const bars = chart.selectAll('rect')
        .data(shopsData)
        .enter()
        .append('rect')
        .attr('x', (d) => xScale(d.name))
        .attr('y', (d) => yScale(d.sales))
        .attr('width', xScale.bandwidth())
        .attr('height', (d) => chartHeight - padding - yScale(d.sales))
        .attr('class', 'chart-bar')
        .classed('highlight', (d, i) => i === 0);

      chart.append('g')
        .attr('class', 'chart-axis')
        .attr('transform', `translate(0, ${chartHeight - padding})`)
        .call(xAxis);

      chart.append('g')
        .attr('class', 'chart-axis')
        .attr('transform', `translate(${padding}, 0)`)
        .call(yAxis);
    }

    // Load the world map data from Natural Earth
    d3.json('https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_50m_land.geojson')
      .then(function(world) {
        // Draw the world map
        svg.selectAll('path')
          .data(world.features)
          .enter()
          .append('path')
          .attr('d', path)
          .attr('fill', '#e5f5f9')
          .attr('stroke', '#999');

        // Draw circular marks for each city
        const cityMarks = svg.selectAll('circle')
          .data(data)
          .enter()
          .append('circle')
          .attr('cx', d => projection([d.lon, d.lat])[0])
          .attr('cy', d => projection([d.lon, d.lat])[1])
          .attr('r', 5)
          .attr('fill', 'steelblue');

        // Highlight the mark of the first city and draw its bar chart on load
        const firstCityMark = cityMarks.filter((d, i) => i === 0);
        firstCityMark.attr('fill', 'orange');

        drawBarChart(data[0]);

        // Create the zoom behavior
        const zoom = d3.zoom()
          .scaleExtent([1, 8])
          .on('zoom', zoomed);

        // Apply the zoom behavior to the SVG element
        svg.call(zoom);

        function zoomed(event) {
          svg.selectAll('path')
            .attr('transform', event.transform);

          cityMarks.attr('transform', event.transform);
        }

        // Mouseover event handler for city marks
        function handleMouseOver(event, d) {
          // Show the tooltip
          tooltip.transition().duration(200).style('opacity', 0.9);

          // Get the mouse coordinates relative to the container element
          const [x, y] = d3.pointer(event);

          // Position the tooltip near the mouse pointer
          tooltip.style('left', (x + 10) + 'px')
            .style('top', (y - 30) + 'px');

          // Generate the list of shops and their sales
          let shopList = '<ul>';
          if (d.shops) {
            d.shops.forEach(shop => {
              const color = shop.sales > 5000 ? 'green' : 'red';
              const textColor = shop.sales > 5000 ? 'white' : 'black';
              shopList += `<li style="color: ${textColor}">${shop.name}: <span style="color: ${color}">${shop.sales}</span></li>`;
            });
          }
          shopList += '</ul>';

          // Update the tooltip content
          tooltip.html(`<strong>${d.city}</strong><br>${shopList}`);
        }

        // Mouseout event handler for city marks
        function handleMouseOut() {
          // Hide the tooltip
          tooltip.transition().duration(200).style('opacity', 0);
        }

        // Click event handler for city marks
        function handleClick(event, d) {
          // Remove highlighting from all city marks
          cityMarks.attr('fill', 'steelblue');

          // Highlight the clicked city mark
          d3.select(this).attr('fill', 'orange');

          // Draw the bar chart for the clicked city
          drawBarChart(d);
        }

        cityMarks
          .on('mouseover', handleMouseOver)
          .on('mouseout', handleMouseOut)
          .on('click', handleClick);
      })
      .catch(function(error) {
        console.log('Error loading map data:', error);
      });
  </script>
</body>
</html>

              
            
!

CSS

              
                
              
            
!

JS

              
                
              
            
!
999px

Console