Skip to content
Advertisement

How to add google map markers based on element entries when user changes it

I am a student who learns web development. I want to add google map markers based on select element entries. So I have created following HTML code to create dropdown list.

<select name="city" class="city" id="city-selection">
    <option selected="selected" value="">Select City</option>
    <option value="City 1">City 1</option>
    <option value="City 2">City 2</option>
    <option value="City 3">City 3</option>
    <option value="City 4">City 4</option>
    <option value="City 5">City 5</option>
    <option value="City 6">City 6</option>
    <option value="City 7">City 7</option>
</select>

To get user input value in every change, I have following JavaScript code.

var selectElement = document.querySelector('#city-selection');
selectElement.addEventListener('change',function(){
    console.log('Changed '+ event.target.value);
    window.cityName = event.target.value;
})

The window.cityName is the global variable which I used to get user input value out of the function & my intention is to use that to add google map markers. So my map code is below.

var map;

function initMap() {
    map = new google.maps.Map(document.getElementById("map"), {
        center: { lat: 7.8731, lng: 80.7718 },
        zoom: 7.8,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        backgroundColor: '#FFF',
        disableDefaultUI: true,
        draggable: false,
        scaleControl:false,
        scrollwheel:false,

        styles:[
        {
            "featureType": "water",
            "elementType": "geometry",
            "stylers": [
                { "visibility": "on" }
            ]
        },
        {
            "featureType": "landscape",
            "stylers": [
                { "visibility": "off" }
            ]
        },
        {
            "featureType": "road",
            "stylers": [
                { "visibility": "off" }
            ]
        },
        {
            "featureType": "administrative",
            "stylers": [
                { "visibility": "off" }
            ]
        },
        {
            "featureType": "poi",
            "stylers": [
                { "visibility": "off" }
            ]
        },
        {
            "featureType": "administrative",
            "stylers": [
                { "visibility": "on" }
            ]
        },
        {
            "elementType": "labels",
            "stylers": [
                { "visibility": "off" }
            ]
        }
        ]
    });

    //colombo marker for city1
    var colomboMark = new google.maps.Marker({
        position:{lat:6.9271, lng:79.8612},
        map:map,
    })

    //pahiyangala marker for city 2
    var pahiyangalaMark = new google.maps.Marker({
        position:{lat:6.6488, lng:80.2163},
        map:map,
    })
}

window.initMap = initMap;

Colombo marker & Pahiyangala marker are only to check marker functionality & those are working properly.

So, is there any way to render those markers based on window.cityName value. I know I can do that using IF condition like below code.

selectElement.addEventListener('change',function(){
    if(window.cityName == "City 1"){
        var colomboMark = new google.maps.Marker({
            position:{lat:6.9271, lng:79.8612},
            map:map,
        })
    }
    else if{
        var pahiyangalaMark = new google.maps.Marker({
            position:{lat:6.6488, lng:80.2163},
            map:map,
        })
    }
})

I have used change event because I need to change global variable value every time when user change the select element option. The issue is when I place above conditional code in google map marker codes JS section, it won’t work.

Any prompt response to this issue will be greatly appreciated.

Advertisement

Answer

There is no need to spam the window superglobal variable – but you do need some means of relating the City 1, City 2 etc etc names to the actual locations. That can easily be done by assigning the relevant details within an object literal ( or JSON variable ) with the CityName as the key. With that key you look up the name,lat and lng values

The following snippet will throw an error referring to google is not defined type thing but should give an idea how to proceed possibly.

let markers = [];

const cities = {
  'City 1': {
    name: 'colombo',
    lat: 6.9271,
    lng: 79.8612
  },
  'City 2': {
    name: 'pahiyangala',
    lat: 6.6488,
    lng: 80.2163
  },
  'City 3': {
    name: 'Geronimo',
    lat: 90,
    lng: 0
  },
  'City 4': {
    name: 'Pocahontas',
    lat: 0,
    lng: 90
  }
};

const addmarker = (lat, lng, name = false) => {
  return new google.maps.Marker({
    title: name,
    name: name,
    position: {
      lat: lat.toFixed(6),
      lng: lng.toFixed(6)
    },
    map: map
  });
};



document.querySelector('select[name="city"]').addEventListener('change', function(e) {
  if (this.value != '' && cities.hasOwnProperty(this.value)) {
  
    // clear previous markers
    markers.forEach(mkr => mkr.setMap(null));
    
    // find the correct city details in cities object
    let obj = cities[this.value];
    
    // add the marker
    markers.push(addmarker(obj.lat, obj.lng, obj.name));

    return true;
  }
  alert('bogus ' + this.value + ' not found')
})
<select name='city' class='city'>
    <option selected hidden disabled>Select City
    <option value='City 1'>City 1
    <option value='City 2'>City 2
    <option value='City 3'>City 3
    <option value='City 4'>City 4
    <option value='City 5'>City 5
    <option value='City 6'>City 6
    <option value='City 7'>City 7
</select>

update: A full example implementing the above code – tested and working.

<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title></title>
        <style>
            #map{
                display:block;
                width:100%;
                height:calc(100vh - 2rem);
                margin:0 auto;
            }
            select[name='city']{
                height:2rem;
                width:100%;
                margin:0 auto;
            }
        </style>
        <script>
            function initMap(){
                let latlng=new google.maps.LatLng( 43.136755, 6.368238 );
                
                const map = new google.maps.Map( document.getElementById('map'), {
                   zoom: 18,
                   scrollwheel: true,
                   center: latlng,
                   mapTypeId: google.maps.MapTypeId.ROADMAP
                });
                
                let markers = [];
                /*
                    depending upon what server you have (ie: PHP)
                    you might generate this list by querying your
                    database... that is usually how it would be 
                    done.
                */
                const cities = {
                  'City 1': {
                    name: 'colombo',
                    lat: 6.9271,
                    lng: 79.8612
                  },
                  'City 2': {
                    name: 'pahiyangala',
                    lat: 6.6488,
                    lng: 80.2163
                  },
                  'City 3': {
                    name: 'Geronimo',
                    lat: 90,
                    lng: 0
                  },
                  'City 4': {
                    name: 'Pocahontas',
                    lat: 0,
                    lng: 90
                  }
                };

                const addmarker = ( lat, lng, name ) => {
                  return new google.maps.Marker({
                    title: name,
                    name: name,
                    position: {
                      lat:lat,
                      lng:lng
                    },
                    map: map
                  });
                };



                document.querySelector('select[name="city"]').addEventListener('change', function(e) {
                  if( this.value != '' && cities.hasOwnProperty( this.value ) ) {
                    markers.forEach( mkr => mkr.setMap( null ) );
                    let obj = cities[ this.value ];
                    
                    markers.push( addmarker( obj.lat, obj.lng, obj.name ) );
                    map.setCenter( new google.maps.LatLng( obj.lat, obj.lng ) );
                    
                    return true;
                  }
                  alert('bogus ' + this.value + ' not found')
                })
            }

        </script>
    </head>
    <body>
        <select name='city' class='city'>
            <option selected hidden disabled>Select City
            <option value='City 1'>City 1
            <option value='City 2'>City 2
            <option value='City 3'>City 3
            <option value='City 4'>City 4
            <option value='City 5'>City 5
            <option value='City 6'>City 6
            <option value='City 7'>City 7
        </select>
        <div id='map'></div>
        <script async defer src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap"></script>
    </body>
</html>
Advertisement