简体   繁体   中英

Initialize Google map after DOM content has loaded

As stated in the title, I have my lng and lat values in my DOM where I'm trying to display the map location based on that 2 values in my DOM however the map isn't display any location as it is in gray color, i suspect that the initMap function is executing before the content has been loaded. Is there a way to initialize the map after the content has been loaded? Here are some of my codes.

Controller

public function show($id)
{

    $report = Report::find($id);

    return view('report',compact('report'));
}

View

<p class="title" id="reportId" data-id="{{$report->id}}" data-lat="{{$report->latitude}}"
    data-lng="{{$report->longitude}}">{{$report->title}}</p>

JavaScript

function initMap() {

    const latData = parseFloat(document.getElementById('reportId').getAttribute('data-lat'));
    const lngData =  parseFloat(document.getElementById('reportId').getAttribute('data-lng'));

    console.log(typeof latData);

    var options = {
        zoom: 15,
        center: {
            lat : latData,
            lng : lngData
        }
    };

    var map = new google.maps.Map(
        document.getElementById("map"),
        options
    );

    var marker = new google.maps.Marker({
        position: {
            lat : 3.119822,
            lng : 101.594800
        },
        map: map
    });
}

This is how the map looks

在此处输入图片说明 EDIT

I did not include this in the beginning because I assumed it was just an issue with JavaScript however, for more information I'm using Laravel 6.5.2 in this project which is the reason why my lat and lng data are inside an element's dataset.

There are nothing special in my laravel codes just getting the data from database through controller methods and display onto my view at the same time setting a data-lat and data-lng so that in my script i can get the coordinates and populate to a google map view.

I have tried one Laravel Google Map library called Googlmapper but unfortunately I'm getting some error from that library too. It is out of topic but you can check it out here .

You can change your body tag to be the following:

<body onload="initMap()">

so that once the dom loads, the map will be initialized.

I would make use of Document.readyState. The Document.readyState property describes the loading state of the document.

The readyState of a document can be one of following:

loading

The document is still loading.

interactive

The document has finished loading and the document has been parsed but sub-resources such as images, stylesheets and frames are still loading.

complete

The document and all sub-resources have finished loading. The state indicates that the load event is about to fire. 

so in your case:

document.addEventListener('readystatechange', event => {
  if (event.target.readyState === 'interactive') {
    //
  }
  else if (event.target.readyState === 'complete') {
    initMap();
  }
});

Source Mozilla

2nd solution: If you will load content via ajax after the dom is already loaded and maybe this take some time, you could set up a time out function, but you will never know when the object is loaded. Then you can track the existence of a dom object and if it is part of the dom content, then read the value and execute your function:

function waitForElement(callback){
    if(window.someVariable){
        callback();
    } else{
        setTimeout(waitForElement(callback), 250);
    }
}

// execute on load:
waitForElement(initMap);

edit: (based on your comment)

seems to me that the map is initialised but without coords. I have only rewritten the coords and created a fiddle. If you have a valid GoogleApiKey, then enter it and the map will be created successfully.

JsFiddle GoogleMaps-example

function initMap() {

    const latData = parseFloat(document.getElementById('reportId').getAttribute('data-lat'));
    const lngData =  parseFloat(document.getElementById('reportId').getAttribute('data-lng'));

    var uluru = {lat: latData, lng: lngData};
    console.log(typeof latData);

    var options = {
        zoom: 15,
        center: uluru
    };

    var map = new google.maps.Map(
        document.getElementById("map"),
        options
    );

    var marker = new google.maps.Marker({
        position: uluru,
        map: map
    });
}

Solved

Apparently... It was a very careless mistake made by me.

which was flipping the values between lat and lng value which results into a undefined location which is why the map did not display location even thought it has been initialized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM