简体   繁体   中英

Change div id and innerHTML content with javascript

Hi i'm trying to change a google map and h3 text with javascript, but it's not working.

What i want to do is display different maps and headers, so basically i want to replace the <div id="map"></div> id with id="map2" to display the Berlin Location instead of Los Angeles. Also i want to replace the <h3 div="textChange">Worlds Finals Season 3 and 6</h3> text with "Worlds Season 5" .

Here's the HTML:

<article>
<div class="container">
<button onclick="changediv()">Season 5</button>
<h3 id="textChange">Worlds Finals Season 3 and 6</h3>
<div id="map"></div>
</div>
</article>

Here's the Javascript:

function initMap() {
    var losAngeles = {
        lat: 34.038037,
        lng: -118.244753
    };
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 4,
        center: losAngeles
    });
    var marker = new google.maps.Marker({
        position: losAngeles,
        map: map
    });

    var berlin = {
        lat: 52.518894,
        lng: 13.407413
    };
    var map2 = new google.maps.Map(document.getElementById('map2'), {
        zoom: 4,
        center: berlin
    });

function changediv() {
    if (document.getElementById("map")) {
        document.getElementById("textChange").innerHTML = "Worlds Finals Season 5";          
        document.getElementById("map").id = "map2";
    }
}

EDIT: "onlick" "div" and parantheses are added, so now the h3 text changes, but the map still won't change, do i have to relaod the page for that to work? Using google maps api.

1) there's a typo here:

<h3 div="textChange">Worlds Finals Season 3 and 6</h3>

change it to:

<h3 id="textChange">Worlds Finals Season 3 and 6</h3>

2) As mentioned in the comment there's another typo in the html

<button onlick="changediv">Season 5</button>

when you trigger a click you want the function to be invoked, you forgot the parenthesis.

<button onlick="changediv()">Season 5</button>

3) last but not least, the map. . Map instances according to the doc should be reused, instead of creating a new instance you should just change the location.

function changeDiv(){
  if (document.getElementById("map")) {
    document.getElementById("textChange").innerHTML = "Worlds Finals Season5";          
    var location = new google.maps.LatLng(berlin.lat, berlin.lng);
    map.panTo(location)
  }

}

You can simply move the map with map.setCenter(LatLng). This method will not use any other markers and will not erase existing markers. You could also move the map via the panTo(LatLng) Both methods are also available after the map has been initialized.

You can read more here https://developers.google.com/maps/documentation/javascript/reference#Map

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