css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

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

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

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.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Find an Address in the US</title>
</head>

<body>
    <div id="map" style="width:100%;height:100%">
        <div id="searchBar">
            <div id="geocoder">
                <i></i>
                <input type="text" id="address" autocomplete="off" placeholder="Search United States">
                <div class="geocoderResult">
                    <ul id="geocoderResult">
                    </ul>
                    <div class="loading hidden ">
                        <img src="https://samples.thinkgeo.com/cloud/example/image/Spinner-1s-50px.gif" alt="loading">
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div id="popup" class="ol-popup hidden">
        <a href="#" id="popup-closer" class="ol-popup-closer"></a>
        <div id="popup-content">
        </div>
        <div class="icon ">
            <img src="https://samples.thinkgeo.com/cloud/example/image/point.png" alt="">
        </div>
    </div>
</body>

</html>
            
          
!
            
              #searchBar {
  top: 20px;
  position: absolute;
  width: 50%;
  left: 25%;
  max-width: none;
  z-index: 1000;
}

#geocoder {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  border-radius: 3px;
  background: #fff;
  width: 100%;
  display: inline-block;
}

#geocoder i{
  width: 20px;
  height: 20px;
  background: url(https://samples.thinkgeo.com/cloud/example/image/seach.png);
  z-index: 1000;
  position: absolute;
  top: 10px;
  left: 10px;
}
#geocoder input{
  display: inline-block;
  font: 15px/20px  sans-serif;
  margin: 0;
  color: rgba(0,0,0,.6);
  padding: 10px 35px ;
  -webkit-appearance: none;
  border: 0px solid ;
  width: 100%;
  border-radius: 3px;
}

#geocoder input:focus{
  outline: none;
}
.geocoderResult{
  position: relative;
}
.loading{
  position: absolute;
  top: 17%;
  left: 45%;
}
#geocoderResult{
  list-style: none;
  padding: 0;
  margin: 0;
}

#geocoderResult li{
  border-top: 1px solid rgba(0,0,0,0.10);
}
#geocoderResult li a{
  padding: 5px 15px;
  display: inline-block;
  width: 100%;
  text-decoration: none;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  font-size: 14px;
  line-height: 20px;
  letter-spacing: 0;
  color: #3887BE;
  cursor: pointer;
}
#geocoderResult li a:hover{
  color: #63b6e5
}
.ol-control:hover {
  background-color: unset;
}

.ol-control:focus {
  outline: unset !important;
}

.ol-full-screen {
  right: unset;
  left: 0.5em;
  top: 5.5em;
  background-color: unset
}

.ol-full-screen button {
  height: 1.2em !important;
  width: 1.2em !important;
  font-size: 1.5em !important;
  cursor: pointer;
  margin: 0px !important;
  background-color: #fff !important;
  color: #2d3c4d !important;
  border: solid 1px #ccc !important;
  box-shadow: 0 1px 2px 0 rgba(34, 36, 38, .15);
  border-radius: 0 0 2px 2px;
}

.ol-full-screen button:hover {
  background-color: #eee !important;
}
.ol-popup {
  position: absolute;
  background-color: white;
  -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  padding: 15px;
  border-radius: 10px;
  border: 1px solid #cccccc;
  bottom: 55px;
  left: -50px;
  min-width: 310px;
  z-index: 1001;
}

.ol-popup:after,
.ol-popup:before {
  top: 100%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}

.ol-popup:after {
  border-top-color: white;
  border-width: 10px;
  left: 48px;
  margin-left: -10px;
}

.ol-popup:before {
  border-top-color: #cccccc;
  border-width: 11px;
  left: 48px;
  margin-left: -11px;
}

.ol-popup-closer {
  text-decoration: none;
  position: absolute;
  top: 2px;
  right: 8px;
}

.ol-popup-closer:after {
  content: "✖";
}

#popup-content p {
  margin-top: 5px;
  margin-bottom: 5px;
}
.address{
  font-family: Arial;
  display: inline-block;
  width: 300px;
  text-decoration: none;
  text-overflow: ellipsis;
  white-space: normal;
  overflow: hidden;
  font-size: 1.1em;
  line-height: 25px;
  letter-spacing: 0;
  color: #333333;
  cursor: pointer;
}
.coodinates{
  font-size: 1.0em;
  color: gray;
}
.icon {
  position: absolute;
  bottom: -62px;
  left: 36px;
}

.hidden {
  display: none;
}
.focus{
  font-weight: 600;
}
            
          
!
            
              const apiKey = 'WPLmkj3P39OPectosnM1jRgDixwlti71l8KYxyfP2P0~' // please go to https://cloud.thinkgeo.com to create

//layer style
let _styles = {
    boundingBox: new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: [0, 0, 255, 0.5],
            width: 1
        }),
        fill: new ol.style.Fill({
            color: [0, 0, 255, 0.1]
        })
    }),
}


let focusIndex = null;
let resultsLength;

//create result layer
const createGeocodingLayer = function () {
    let vectorLayer = new ol.layer.Vector({
        source: new ol.source.Vector({
            features: []
        }),
        style: function (feature) {
            let key = feature.get('type');
            let style = _styles[key];
            return style;
        }
    });
    vectorLayer.set('name', 'geocodingLayer');
    return vectorLayer;
};


//render base map 
let baseMap = new ol.mapsuite.VectorTileLayer('https://cdn.thinkgeo.com/worldstreets-styles/1.0.0/light.json', {
    apiKey: apiKey,
});

// This function will create and initialize our interactive map.
// We'll call it later when our POI icon font has been fully downloaded,
// which ensures that the POI icons display as intended.
let map;
let view = new ol.View({
    center: ol.proj.fromLonLat([-96.79620, 32.79423]),
    maxZoom: 19,
    maxResolution: 40075016.68557849 / 512,
    zoom: 3,
    minZoom: 2
})
let initializeMap = function () {
    map = new ol.Map({
        layers: [baseMap, geocodingLayer = createGeocodingLayer()],
        target: 'map',
        loadTilesWhileAnimating: true,
        loadTilesWhileInteracting: true,
        view: view
    });

    map.addControl(new ol.control.FullScreen());
}

//render result

//   Elements that make up the popup.
const container = document.getElementById('popup');
container.classList.remove('hidden');
const content = document.getElementById('popup-content');
const closer = document.getElementById('popup-closer');

let overlay = new ol.Overlay({
    element: container,
    autoPan: false,

});

closer.onclick = function () {
    overlay.setPosition(undefined);
    let source = geocodingLayer.getSource();
    source.clear();
    closer.blur();
    return false;
};

const popUp = function (address, coordinates, type) {
    overlay.setPosition(ol.proj.fromLonLat(coordinates));
    map.addOverlay(overlay);
    content.innerHTML = `<p class="address">${address}</p><p class="coodinates">${coordinates[1]},${coordinates[0]}</p>`
}

const geocoderResultNode = document.getElementById('geocoderResult');

//Renter result
const renderResult = ({
    locations
}) => {
    document.querySelector('.loading').classList.add('hidden');
    if (locations.length > 0) {
        resultsLength = locations.length;
        let str = '';
        let i = -1
        for (const item of locations) {

            i = i + 1;
            str += `<li><a data-coordinatesX=${(item.locationPoint.pointX).toFixed(6)} data-coordinatesY=${(item.locationPoint.pointY).toFixed(6)} data-index=${i}   data-boundingBox="${item.boundingBox}"" data-type=${item.locationType}> ${item.address} </a></li>`
        }
        geocoderResultNode.innerHTML = str;
    } else {
        geocoderResultNode.innerHTML = ''
    }
}

//re
const renderBestMatchLoaction = (coordinatesX, coordinatesY, boundingBox, address, type) => {
    overlay.setPosition(undefined);
    let source = geocodingLayer.getSource();
    source.clear();
    coordinates = [parseFloat(coordinatesX), parseFloat(coordinatesY)];

    let format = new ol.format.WKT();
    let wktFeature = format.readFeature(boundingBox, {
        dataProjection: 'EPSG:4326',
        featureProjection: 'EPSG:3857'
    });
    geocodingLayer.getSource().addFeature(wktFeature);
    if (type === 'Street') {
        view.animate({
            center: ol.proj.fromLonLat([parseFloat(coordinatesX), parseFloat(coordinatesY)]),
            zoom: 18,
            duration: 0
        });

    } else {
        wktFeature.set('type', 'boundingBox');
        view.fit(wktFeature.getGeometry(), {
            padding: [20, 20, 20, 20]
        })
    }

    popUp(address, coordinates, type);
}

//Geocoder address
const geocoder = (val) => {
    const baseURL = 'https://cloud.thinkgeo.com/api/v1/location/geocode/';
    let url = `${baseURL}${val}?apikey=${apiKey}&MaxResults=5`;
    const time = 5000;
    let timeout = false;
    let request = new XMLHttpRequest();
    let timer = setTimeout(() => {
        timeout = true;
        request.abort();
    }, time);
    request.open("GET", url);

    request.onreadystatechange = () => {
        if (request.readyState !== 4) {
            return;
        }
        if (timeout) {
            document.querySelector('.loading').classList.add('hidden');
            return;
        }
        clearTimeout(timer);
        if (request.status === 200) {
            let data = JSON.parse(request.response).data;
            renderResult(data)
        }
    };
    request.send(null);
}

//Tool function
const removeClass = () => {
    const nodeList = document.querySelectorAll('#geocoderResult a');
    for (let node of nodeList) {
        node.classList.remove('focus');
    }
}

const obtainParameter = (target) => {
    let boundingBox = target.getAttribute('data-boundingBox');
    let coordinatesX = target.getAttribute('data-coordinatesX');
    let coordinatesY = target.getAttribute('data-coordinatesY');
    let address = target.innerText;
    let type = target.getAttribute('data-type');
    renderBestMatchLoaction(coordinatesX, coordinatesY, boundingBox, address, type)
}

const compareFocusIndex = (flag) => {
    const nodeList = document.querySelectorAll('#geocoderResult a');
    for (let node of nodeList) {
        if (Number(node.getAttribute('data-index')) == focusIndex) {
            if (flag) {
                node.classList.add('focus');
                return
            } else {
                address.value = node.innerText;
                geocoderResultNode.innerHTML = '';
                obtainParameter(node)
            }
        }
    }
}

const moveFocus = (dir) => {
    removeClass()
    if (document.querySelector('.loading').classList.contains('hidden')) {
        if (focusIndex == null || focusIndex == resultsLength - 1) {
            focusIndex = 0
        } else if (focusIndex == -1) {
            focusIndex = resultsLength - 1
        } else {
            focusIndex = focusIndex + dir
        }
    }
    compareFocusIndex(true)
}

//User interaction
let timer = null;
const address = document.getElementById('address')
address.addEventListener('input', (e) => {
    clearTimeout(timer);
    timer = setTimeout(() => {
        overlay.setPosition(undefined);
        let source = geocodingLayer.getSource();
        source.clear();
        let value = address.value;
        focusIndex = null;
        if (value) {
            document.querySelector('.loading').classList.remove('hidden');
            geocoder(value)
        } else {
            geocoderResultNode.innerHTML = ''
        }
    }, 200);
})
document.getElementById('geocoderResult').addEventListener('click', (e) => {
    let target = e.target;
    if (target.nodeName == 'A') {
        removeClass();
        address.value = target.innerText;
        geocoderResultNode.innerHTML = '';
        focusIndex = Number(target.getAttribute('data-index'));
        obtainParameter(target)
    }
})

document.body.addEventListener('keydown', (e) => {
    switch (e.keyCode) {
        //up
        case 38:
            e.preventDefault();
            moveFocus(-1);
            break;
            // down
        case 40:
            e.preventDefault();
            moveFocus(1);
            break;
        case 13:
            if (focusIndex !== null) {
                compareFocusIndex(false)
            }
            break;
    }
})

WebFont.load({
    custom: {
        families: ["vectormap-icons"],
        urls: ["https://cdn.thinkgeo.com/vectormap-icons/2.0.0/vectormap-icons.css"]
    },
    // The "active" property defines a function to call when the font has
    // finished downloading.  Here, we'll call our initializeMap method.
    active: initializeMap
});
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console