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

Save Automatically?

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

              
                <h1>Shared Realtime Photo Map powered by <a href="https://sanity.io/?utm_source=css-tricks&utm_campaign=csstricks">sanity.io</a></h1>
<div class="wrapper">
    <div id="app">
      <span id="loading">Loading...</span>
    </div>
  </div>
  <footer>
    <p>This is a demo using structured content in <a href="https://sanity.io/?utm_source=css-tricks&utm_campaign=csstricks">sanity.io</a></p>
  </footer>
</div>
              
            
!

CSS

              
                :root {
  --primary-color: #aef;
  --background-color: #1d1e22;
  --border-radius: 3px;
}
body {
  padding: 1em;
  line-height: 1.2;
  background: var(--background-color);
  color: #fff;
}

a {
  color: var(--primary-color);
}
.container {
  display: grid;
  grid-gap: 1rem;
  grid-template-columns: 1fr;
  grid-template-areas: 
    "info"
    "dropzone"
    "alert"
    "map";
}
@media only screen and (min-width: 600px) {
  .container {
    grid-template-columns: 5fr 2fr;
  grid-template-areas: 
    "info dropzone"
    "alert alert"
    "map map";
}
}


.leaflet-container {
  grid-area: map;
  position: relative;
  height: 400px;
  width: 100%;
  background: var(--background-color);
}


.info {
  grid-area: info;
}

footer {
  display: block;
}
pre {
  font-size: 11px;
  overflow: auto;
  white-space: pre-wrap;
  overflow-wrap: break-word;
}
.preview__image {
 width: 100%;
 margin-bottom: 1rem;
}
.preview__alert {
  padding: 1em;
  background: #ff5f5f;
  margin-bottom: 0.5rem;
  border-radius: var(--border-radius);
}
.dropzone {
  grid-area: dropzone;
  padding: 1em 0;
}

.dropzone__widget {
  margin: 1rem 0;
  padding: 2rem;
  border: 1px #ddd;
  background-color: #aef;
  border-radius: 3px;
  text-align: center;
  fill: rgba(20,50,120,0.5);
  color: #000;
}

.popup__image {
  width: 100%;
  max-width: 500px;
}

button {
  border: 2px solid #aef;
  background: #aef;
  margin-bottom: 0.5rem;
  border-radius: var(--border-radius);
}
.metadata {
  background: #fff;
  color: black;
  width: auto;
  margin: 1em;
  padding: 1em;
  top: 1em;
}
.ReactModal__Overlay--after-open {
  overflow: hidden;
  position: fixed;
  width: 100%;
  height: 100%;
  max-height: 100vh;
  overflow-y: auto;
  z-index: 9999;
}
              
            
!

JS

              
                // set up React Leaflet
const { Map: LeafletMap, TileLayer, Marker, Popup } = ReactLeaflet

ReactModal.setAppElement('#app')

/**
 * Set up the Sanity client.
 */
const client = SanityClient({
  projectId: 'anokeucs',
  dataset: 'sanitycsstricks',
  useCdn: false
})

/**
 * This is a GROQ query. Learn more at
 * https://docs.sanity.io/
 */
const query = `*[_type == 'sanity.imageAsset' && defined(metadata.location) && !(coalesce(_id in $ids, false))][0..100]|order(_createdAt asc)`

class ImageExample extends React.Component {
  constructor () {
    super()
    this.state = {
      exif: '',
      filesToBeSent: [],
      hasError: false,
      lat: 51.505,
      lng: -0.09,
      preview: null,
      result: [],
      uploaded: false,
      uploading: false,
      zoom: 1
    }

    this.cancelUpload = this.cancelUpload.bind(this)
    this.closeDialog = this.closeDialog.bind(this)
    this.fetchData = this.fetchData.bind(this)
    this.handleDropRejected = this.handleDropRejected.bind(this)
    this.onDrop = this.onDrop.bind(this)
    this.openDialog = this.openDialog.bind(this)
    this.uploadImages = this.uploadImages.bind(this)
  }
  componentDidCatch (error, info) {
    // Display fallback UI
    this.setState({ hasError: true })
    // You can also log the error to an error reporting service
    console.error(error, info)
  }
  componentDidMount () {
    // Do the initial datafetching
    this.fetchData()
    // Set up an listener
    const subscription = client
      .listen(query, { ids: this.state.result.map(({ _id }) => _id) })
      .subscribe(({ result }) => this.fetchData(result))
  }
  cancelUpload () {
    this.setState({ preview: '', filesToBeSent: [], uploaded: false })
  }

  fetchData (newResult) {
    const { result = [] } = this.state
    client
      .fetch(query, { ids: result.map(({ _id }) => _id) })
      .then((result = []) => {
        const renderResults = [...result, ...this.state.result]
        this.setState({
          result: newResult ? [...renderResults, newResult] : renderResults
        })
      })
      .catch(console.error)
  }
  handleDropRejected (...args) {
    console.log('reject', args)
    this.setState({ uploading: false, uploaded: false })
  }
  onDrop (acceptedFiles, rejectedFiles) {
    const [{ preview }] = acceptedFiles
    let filesToBeSent = this.state.filesToBeSent
    filesToBeSent.push(acceptedFiles)
    this.setState({ filesToBeSent, preview })
  }
  openDialog(_id) {
    this.setState({ showModal: _id })
  }
  closeDialog(_id) {
    this.setState({ showModal: '' })
  }

  uploadImages () {
    const { filesToBeSent = [] } = this.state
    this.setState({ uploading: true })
    filesToBeSent.forEach(file => {
      client.assets
        .upload('image', file[0], { extract: ['palette', 'location', 'exif'] })
        .then(document => {
          if (!document.metadata.location) {
            this.setState({ missingLocation: true })
          }
          this.setState({ uploading: false, uploaded: true })
        })
        .catch(error => {
          console.error("¯_(ツ)_/¯ Something didn't work:", error.message)
          this.setState({ uploading: false })
        })
    })
  }

  render () {
    const {
      result = [],
      preview = '',
      uploading = false,
      uploaded = false,
      exif = {},
      lat,
      lng,
      missingLocation
    } = this.state
    const position = [lat, lng]

    return (
      <div className="container">
        <article className="info">      
      <p>
        Upload a photo with geolocation data to see it on the map below.</p><p><em>Be mindful that you'll be sharing the location data!</em> <br />If you want to have your photo deleted, <a href="mailto:[email protected]">tell us</a>!
      </p>
    </article>
        <div className="dropzone">
        {!preview &&
          Dropzone && (
            <Dropzone
              className="dropzone__widget"
              onDrop={this.onDrop}
              accept="image/jpeg,image/jpg,image/tiff,image/gif"
              multiple={false}
              onDropRejected={this.handleDropRejected}
            >
            <svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'>
              <path d='M0 0h24v24H0z' fill='none' />
              <path d='M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM14 13v4h-4v-4H7l5-5 5 5h-3z' />
            </svg><br />
              Drag a photo here with location data or click this square to
              activate a file uploader!
            </Dropzone>
          )}
        {preview &&
          !uploaded && (
            <div className="preview">
              <img
                className="preview__image"
                src={preview}
                alt="image preview"
              />
              <button
                className="preview__button"
                onClick={this.uploadImages}
                disabled={uploading}
              >
                {uploading ? 'Uploading…' : 'Upload!'}
              </button>
            </div>
          )}
        {uploaded &&
          missingLocation && (
            <div className="preview__alert">
              <strong>🤪Whooops…</strong><br />This photo didn't have any geolocation location data. Try another one?
            </div>
          )}
        {preview && (
          <button className="preview__button" onClick={this.cancelUpload}>
            Upload another photo
          </button>
        )}
        </div>

        <LeafletMap
          scrollWheelZoom={false}
          center={position}
          zoom={this.state.zoom}
        >
          <TileLayer
            attribution="&copy; <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors"
            url="http://{s}.tile.osm.org/{z}/{x}/{y}.png"
          />
          {result &&
            result.map(
              ({ _id, url = '', metadata: { exif, location = {} } = {} }) => (
                <div key={_id}>
                  <Marker position={[location.lat, location.lon]}>
                    <Popup>
                      <img className="popup__image" src={`${url}?w=150`} />
                      <button onClick={() => this.openDialog(_id)}>
                        See EXIF details
                      </button>.
                    </Popup>
                  </Marker>{' '}
<ReactModal
              isOpen={this.state.showModal === _id}
              contentLabel="Minimal Modal Example"
              id={_id}
              OnAfterClose={() => document.body.style.overflow = 'hidden' }
OnRequestClose={() => document.body.removeAttribute('style') }
              className="metadata"
            >
                    <button onClick={() => this.closeDialog(_id)}>Close</button>
  <div>
                    <img className="popup__image" src={`${url}?w=500`} />
                    <pre>{JSON.stringify(exif, null, 2)}</pre>
  </div>
                  </ReactModal>
                </div>
              )
            )}
        </LeafletMap>
      </div>
    )
  }
}

ReactDOM.render(<ImageExample />, document.getElementById('app'))

              
            
!
999px

Console