"Customize the centering offset of Google Maps based on the width of

Struggling to implement a design using my code, but it's not behaving as expected. When the old width is larger than the new width, the offset Center should be -50. And when the old width is smaller, the offset Center should be 50.

The offset Center works without the need for "if" statements, but this means the offset will be fixed at 50 or -50 whenever the user resizes the window.

The rectangles on the map are only meant to cover the names.

html

CSS

#map{
    width: 100%;
    height: 400px;
}

JS

<script async defer
src="https://maps.googleapis.com/maps/api/js?key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&callback=initMap">
</script>


<script>
function oh_ow() {
        var oh = $(window).height();
        var ow = $(window).width();
        return ow;
}    
    var old_w = oh_ow()
    alert(old_w );

        alert(ow);
    function initMap() {
  var uluru = {lat: 62.26393, lng: 82.386004};
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 16,
    center: uluru
  });
  var marker = new google.maps.Marker({
    position: uluru,
    map: map
  });



function offsetCenter(latlng, offsetx, offsety) {

    
    var scale = Math.pow(2, map.getZoom());

    var worldCoordinateCenter = map.getProjection().fromLatLngToPoint(latlng);
    var pixelOffset = new google.maps.Point((offsetx/scale) || 0,(offsety/scale) ||0);

    var worldCoordinateNewCenter = new google.maps.Point(
        worldCoordinateCenter.x - pixelOffset.x,
        worldCoordinateCenter.y + pixelOffset.y
    );

    var newCenter = map.getProjection().fromPointToLatLng(worldCoordinateNewCenter);

    map.setCenter(newCenter);

}

google.maps.event.addDomListener(window, 'resize', function() {

//---------------------------------------------    
var rtime;
var timeout = false;
var delta = 200;
$(window).resize(function() {
    rtime = new Date();
    if (timeout === false) {
        timeout = true;

        setTimeout(resizeend, delta);
    }
});
function resizeend() {
    if (new Date() - rtime < delta) {
        setTimeout(resizeend, delta);
    } else {
        timeout = false;
          var nh = $(window).height();
          var nw = $(window).width();
          
       if(nw > old_w){
            offsetCenter(map.getCenter(),50,-0);
        }else if(nw < old_w){
            offsetCenter(map.getCenter(),-50,-0);
        }


    }               
}    
//---------------------------------------------    
});





}



</script>

Looking for a responsive version of How to offset the center point in Google maps api V3

Your help would be greatly appreciated.

Answer №1

It seems that achieving this can be done using the setCenter, panTo, and panBy methods.

function initMap() {
  var uluru = {
    lat: 25.26393,
    lng: 55.386004
  };
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 16,
    center: uluru
  });
  var marker = new google.maps.Marker({
    position: uluru,
    map: map
  });

  var winWidth = $(window).width();
  panMap();

  $(window).resize(function() {
    map.setCenter(uluru);
    panMap();
  });

  google.maps.event.addListener(map, 'zoom_changed', function() {
    map.panTo(uluru);
    panMap();
  });

  function panMap(xChange){
    var winWidth = $(window).width();
    if(winWidth > 671){
      map.panBy(xChange || -170, 0);
    }
  }

}

You can modify the -170 value to adjust the position accordingly.

Check out the demo here : https://jsbin.com/fasawofofa/1/edit?html,output

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the capabilities of data processing in Node.js

I've been attempting to read data from a locally stored JSON file, organize it into individual JS objects, and add them to a queue. However, I'm struggling to find a way to test my parsing function to ensure it's functioning correctly. My cu ...

Stopping the continuous re-sending of a script via Ajax when a key is pressed

My script is set up to save messages into a database when the enter key is pressed. <textarea class="comment" name="comment" id="comment" onKeyPress="return checkSubmit(event)" onKeyDown="return checkTypingStatus(event)" >Comment/Reply</textarea& ...

What is the process for redirecting to a different URL when the button is clicked?"

I am trying to display Home.js at localhost/posts, but when the button is clicked, it displays information at the auth.js URL. How can I link the button so that if the login information is correct, it redirects to "localhost/posts" instead of rendering its ...

The responsive table works flawlessly in all platforms except for the default iOS 7 mail application

When using the default iOS 7 (iOS 7.1.1) mail app, there seems to be an issue with rendering a table correctly. Browsers like Chrome, Firefox, and Safari (latest versions) display both the desktop and mobile views perfectly. However, Internet Explorer only ...

Typescript is throwing an error when trying to use MUI-base componentType props within a custom component that is nested within another component

I need help customizing the InputUnstyled component from MUI-base. Everything works fine during runtime, but I am encountering a Typescript error when trying to access the maxLength attribute within componentProps for my custom input created with InputUnst ...

Sharing the success result from an AJAX call to a different PHP page

I'm trying to show the result of $("#searchresults").html(data) on another page using the code below. $.ajax({ type: "POST", url: base_url + 'front/searchresult', data: data, success: function(data) { alert("test"); var val ...

Is there a way to calculate the number of days between two selected dates using the bootstrap date range picker?

I recently implemented the bootstrap daterange picker for selecting start and end dates, and it's been working perfectly. However, I now have a requirement to display the count of days selected. Here's my current code: $('input[name="datera ...

Safari was unable to load the webpage due to a lack of response from the server

One of the pages on my ASP.NET website is experiencing slow loading times. While it works fine on all Android and MAC operating systems, as well as on iOS versions except for 10.0.0.2 with Safari browser. When attempting to load the page on Safari in ...

Using Thymeleaf within Javascript code to generate a URL?

Here is my question: The project's base URL is : The test page URL is :, and on this page, I have included a JavaScript file called datatable.packer.js using the following code: <script type="text/javascript" th:src="@{/resources/js/datatable ...

Why am I receiving undefined for req.user in passportjs?

After setting up passportJS with my node express app, I encountered an issue where the req.user is undefined when making a login/register request. I am not sure what went wrong or if I missed something in the configuration of passport js. In my setup, I us ...

Having difficulty aligning block element in the center horizontally

I am struggling with centering elements for a list of upcoming blog posts. The Postlist component is integrated into my App.js file. Although I successfully centered the navigation bar following the method described here in the Horizontally section and spe ...

Utilizing the power of Angular's $resource within a factory to showcase information stored in a deeply nested

Just starting to explore the world of $resource concepts and facing a challenge with a piece of code that involves fetching data from a nested JSON. I've created a factory method that successfully retrieves the data and I can see it in the response he ...

Using Selenium with C# to find elements within a chart

I am trying to locate and interact with the stimulusFrequency circles on this chart so that I can click and drag them. <svg class="svg-graph-content graphEventHandler ng-valid" ng-model="hearingGraph" viewBox="0 0 470 355" preserveAspectRatio="none"> ...

What is the optimal number of parameters in JavaScript?

After stumbling upon a question on StackOverflow discussing the number of parameters in JavaScript functions (How many parameters are too many?), I started pondering if there is a real limitation on how many parameters a JS function can have. test(65536 ...

Creating a new row with a dropdown list upon clicking a button

I want to include a Textbox and dropdown list in a new row every time I click a button. However, I seem to be having trouble with this process. Can someone assist me in solving this issue? Thank you in advance. HTML <table> <tr> ...

The live feature is operational, but unfortunately the on feature is not functioning

I am facing an issue in my code where replacing .live with .on is not working. I have been trying to identify the problem but haven't found a solution yet. $(document).ready(function () { /* Reading the data from XML file*/ $.ajax({ ...

Using external variables as arguments in a Node.js function

For the purpose of establishing a connection with mlab, I am passing the URL into a function. Below is the function in question: function connectToDb(mongoURL) { mongoose.Promise = global.Promise; mongoose.connect(mongoURL, (err, db) => { ...

What is the method for interacting with an embedded alert using SeleniumIDE?

When working with HTML, I came across the following code snippet (it's not from my website): <script> alert('1'); </script> My challenge now is to test this code using Selenium IDE and ensure that the alert will be clicked. How ...

Switching the Cursor Image When Hovering Over a Different Image with JavaScript or jQuery

I have been trying to implement a feature where I hover over an image and a custom cursor (150x150) appears. Despite my best efforts, the hover effect is not as smooth as I would like it to be. Can someone please provide guidance on how to achieve this sea ...

Exploring the possibilities of using jQuery to access global variables in node.js

My issue has 3 main components. I need to declare a server-side (node.js) variable to store data for the duration of the server run, specifically just a number. I must send a number from the client (jQuery) to the server in order to update the server v ...