Jump to content

setCenter() in Google Maps API to change center on map after click on button ?


sashavalentina

Recommended Posts

I have four different locations that is displayed from a set of arrays of coordinates. I'd like to change the shown location in my Google Map by click on the buttons that are coordinated.

I tried to use a Javascript function with setCenter(), but unfortunately it doesn't work. Has anyone an idea what might be wrong?

i checked it in inspection mode, and i see this in my button element

<button type="button" onclick="javascript:'undefined'">1.5298600000000002,110.36003000000001</button>

here is the full code

<div class="col-12 form-group mt-5">
      <div class="card" style="box-shadow: 0 0 8px rgb(0, 0, 0, 0.3)">
        <h6 class="text-muted text-center p-3 mt-2">Map</h6>
        <div class="card-body">
          <div id="googleMap" style="width: 100%; height: 400px"></div>
        </div>
      </div>
    </div>
    <div id="results"></div>

 <script>
      function myMap() {
        var mapProp = {
          position: new google.maps.LatLng(32.735316, -117.149046),
          zoom: 1,
        };
        var map = new google.maps.Map(
          document.getElementById("googleMap"),
          mapProp
        );
      }
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=MYAPIKEY&callback=myMap"></script>
 <script>
      var coord_lists;
      load(coord_lists);

      function load() {
        const coordinates_lists = [];

        console.log(coordinates_lists);
        const map = new google.maps.Map(document.getElementById("googleMap"), {
          zoom: 5,
          center: coordinates_lists[0],
          mapTypeId: google.maps.MapTypeId.ROADMAP,
        });
        map.setZoom(9);
        console.log(map);

        var locations = [
          [1.5298600000000002, 110.36003000000001],
          [1.52872, 110.36453],
          [1.5278, 110.36775000000002],
          [1.5273500000000002, 110.37160000000002],
        ];

        function ZoomAndCenter() {
          map.setCenter(
            new google.maps.LatLng(locations[i][0], locations[i][1])
          );
          map.setZoom(15);
        }
        var result = "";
        for (var i = 0; i < locations.length; i++) {
          result =
            result +
            "<button type='button' onclick=\"javascript:'" +
            ZoomAndCenter(locations[i]) +
            "'\">" +
            locations[i] +
            "</button>" +
            "<br>";
        }
        document.getElementById("results").innerHTML = result.toString(result);

        var marker, i;
        var markers = [];

        for (i = 0; i < locations.length; i++) {
          marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i][0], locations[i][1]),
            map: map,
          });
        }
      }
    </script>

 

Link to comment
Share on other sites

This

"<button type='button' onclick=\"javascript:'" +
ZoomAndCenter(locations[i]) +

isn't going to work. What it does is actually call the ZoomAndCenter function right at the moment that you're creating the button, when what you want is to have that function called when you click the button. As part of the onclick.

Calling the function, which returns nothing, is why you see

onclick="javascript:'undefined'"

when you inspect the button.

This code is rather old in its practices. Modern Javascript has you creating a button element like with document.createElement, attaching an event handler with addEventListener, then inserting the button into the document.

That said, my preferred approach is to throw data attributes on a button and pull them out in the event handler.

<button type="button" data-center-latitude="1.52986" data-center-longitude="110.36">Click me</button>

I also still use jQuery because it's much easier than dealing with DOM stuff manually.

$("#results button[data-center-latitude][data-center-longitude]").each(function() {
	const lat = parseFloat(this.dataset.centerLatitude);
	const lng = parseFloat(this.dataset.centerLongitude);
	const latlng = new google.maps.LatLng(lat, lng);

	new google.maps.Marker({
		position: latlng,
		map,
	});

	$(this).on("click", function() {
		map.setCenter(latlng);
		map.setZoom(15);
	});
});

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.