skip to Main Content

I am new to google maps and following is code snippet of google maps
The marker is in middle of the screen but how can I appear at top center (top middle as illustrated in image) of the screen.

function initMap() {
  const myLatLng = { lat: -25.363, lng: 131.044 };
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: myLatLng,
  });

  new google.maps.Marker({
    position: myLatLng,
    map,
    title: "Hello World!",
  });
}

window.initMap = initMap;

enter image description here

2

Answers


  1. Simply, to the specified location you can use the Map.panTo() method and to set the zoom level you can use the Map.setZoom() method.

    You can test it to see if it’s useful to you, and if you want any changes, just let me know and I’ll make them.

    function initMap() {
      const myLatLng = { lat: -25.363, lng: 131.044 };
      const map = new google.maps.Map(document.getElementById("map"), {
        zoom: 4,
        center: myLatLng,
      });
    
      const marker = new google.maps.Marker({
        position: myLatLng,
        map,
        title: "Hello World!",
      });
    
      // Set the map center to the marker position
      map.panTo(myLatLng);
    
      // Set the zoom level to 12
      map.setZoom(12);
    }
    
    window.initMap = initMap;
    <!DOCTYPE html>
    <html>
      <head>
        <title>Google Maps Example</title>
        <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
        async defer></script>
        <style>
          #map {
            height: 400px;
            width: 100%;
          }
        </style>
      </head>
      <body>
        <div id="map"></div>
      </body>
    </html>
    Login or Signup to reply.
  2. PanTo(): https://developers.google.com/maps/documentation/javascript/reference/map#Map.panTo

    This function is used to set the center position of the map:

    panTo(latLng)

    Parameters:
    latLng: LatLng|LatLngLiteral The new center latitude/longitude of the map.

    Return Value: None

    Changes the center of the map to the given LatLng. If the change is less than both the width and height of the map, the transition will be smoothly animated.


    So this will you to set center position according to marker.

    function initMap() {
      const myLatLng = { lat: -25.363, lng: 131.044 };
      const map = new google.maps.Map(document.getElementById("map"), {
        zoom: 4,
        center: myLatLng,
      });
    
      new google.maps.Marker({
        position: myLatLng,
        map,
        title: "Hello World!",
      });
    
      // map position set to center according to marker position
      map.panTo(myLatLng);
    }
    
    window.initMap = initMap;
    

    This will also help you:
    Google Maps PanTo OnClick

    UPDATE

    http://jsfiddle.net/kamrankb/6mxopg0n/2/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search