NewSignature / us-map

An interactive map of the United States using Raphaël
BSD 2-Clause "Simplified" License
279 stars 184 forks source link

How might I create a single state? I see getStateShapes(). Can I use that to create a single state? #35

Open sroberson opened 10 years ago

sroberson commented 10 years ago

I have an app where I show the entire US, but when you click on a state, you'll then see a single state. I'd like to show the outline of that one state and am wondering how I might do that.

Thanks, Scott

sroberson commented 10 years ago

I changed the plugin to add a new property: this.stateRawPath.

So, when the code is looping through each state grabbing it's path information, I add the raw path string to this property.

Then, I added this property to the getStateShape method:

getStateShapes: function() {
  if(this._getStateShapes) {
    return this._getStateShapes;
  }

  this._getStateShapes = {};

  for(var stateName in this.stateShapes) {
    this._getStateShapes[stateName] = {
      shape: this.stateShapes[stateName],
      hitArea: this.stateHitAreas[stateName],
      labelBacking: stateName in this.labelShapes ? this.labelShapes[stateName] : null,
      labelText: stateName in this.labelTexts ? this.labelTexts[stateName] : null,
      labelHitArea: stateName in this.labelHitAreas ? this.labelHitAreas[stateName] : null,
      name: stateName,
      rawPath: this.stateRawPath[stateName]     //    *** Added by Scott R. ***
    };
  }

  return this._getStateShapes;
}

Therefore, when I need to build a single state, I can do this:

var statePolygon = $("#map").data('pluginUsmap').getStateShapes()[state.toUpperCase()]['rawPath'];

//sometimes the paths don't contain the final Z
if (statePolygon.charAt(statePolygon.length-1).toUpperCase() !== "Z") {
    statePolygon = statePolygon + " Z";
    log('added a final Z');
    $("#map").data('pluginUsmap').getStateShapes()[state.toUpperCase()]['rawPath'] = statePolygon;
}

// remove any previously created svg's.... there's probably a Raphael method to do this.
 $("#statemap").find('> *').remove();

var p,
      width = 175,
      height = 200,
      paper = Raphael(document.getElementById("statemap"));

var bbox = Raphael.pathBBox( statePolygon );  // Handy function to retrieve a bounding box without instantiating a path

//  Calculate larger of the two dimensional quotients
var scale = Math.max( bbox.width / width, bbox.height / height );

/*  Finally, transform the path such that it is translated to have its origin at 0,0 and scaled in such a way that it will fill the SVG */

var transformedPathString = Raphael.transformPath( statePolygon,
                [ "T", 0 - bbox.x, 0 - bbox.y,   /* Shift up and left so upper-left extent corresponds to 0,0 */
                    "S", 1.0 / scale, 1.0 / scale, 0, 0 ] );

paper.path(transformedPathString);