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.

JavaScript

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

JavaScript

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.

JavaScript

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.

JavaScript

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.

JavaScript
JavaScript

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

JavaScript
Advertisement