0

I have more than 1000 street lights across my town and they are all saved in MYSQL table. For a person to log a specific faulty street light I need to have them displayed and allow a user to click on the faulty one to get the coordinates of the street light.

Can someone help me on how to listen to mouse click on a specific point in google map so to get both the longitude and latitude out of that point?

Many thanks in advance.

  • Possible duplicate of [Get Latitude and Longitude on click event from Google map](https://stackoverflow.com/questions/9247006/get-latitude-and-longitude-on-click-event-from-google-map) – JasonB Dec 11 '17 at 06:17
  • It is not a duplicate since I need to only allow clicks on certain points only and now click on the whole map. – user3448324 Dec 11 '17 at 06:22

1 Answers1

0

To display them on the map and respond to clicks on those particular street lights, we could loop through your stored locations and add markers to the map for all of your lights with a click event listener added to those markers.

Here's an example that has an array of two latlon objects to show how to loop through your locations and attach the event handler to all of the markers.

<div id="map" style="height:200px;"></div>
<script>
      var map;
      var lightLocations = [
          {lat: -34.397, lng: 150.644},
          {lat: -34.350, lng: 150.704}
      ];

      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 10
        });
        var markerClicked = function(event) {
            // here's where you do what you need to do with the info
            alert(this.position);
        }
        lightLocations.forEach( function(element) {
            var marker = new google.maps.Marker({
                 position: element,
                 map: map
            });
            marker.addListener( 'click', markerClicked );
        });

      }
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?callback=initMap"
    async defer></script>
JasonB
  • 6,243
  • 2
  • 17
  • 27
  • Thank you very much for your code which makes a lot of sense. Tonight I will test the code and will let you know. – user3448324 Dec 11 '17 at 07:14
  • Glad to hear it! Note that you will see a Google Maps API warning if you don't add your own API key to the maps api url – JasonB Dec 11 '17 at 07:28