How can I give a name to a marker on Google Maps?

Hello there!

I’m trying to learn some new things with Javascript. This time with Google Maps.

I already created a script for searching for a place. When I click on search it shows me the place on Google Maps with a marker. The next thing I want to do is to give the marker a name by means of an input field when I move with my cursor over it, just like this pic. This is what I’m trying to do.example

I already tried some things but I can’t figure it out. As you can see in my script I tried some things with the variable ‘namemarker’.

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Place marker with name</title>
</head>

<body>
        <div >
            <h1>Place marker with name</h1>
        </div>
    <div>
        <div>
            <div>
                <div>
                    <h2>Place and name marker</h2>
                </div>
                <div>
                    <form>
                        <div>
                            <div>
                                Place
                                <input id="place" type="text">
                            </div>
                            <div>
                                Name Marker<input id="namemarker" type="text">
                                <div>
                                    <button id="search">search</button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <div>
                <div>
                    <div>
                        <h1>MAP</h1>
                    </div>
                </div>
                <div>
                    <div class="divmap"></div>
                </div>
            </div>
        </div>
    </div>

<script src="js/main.js"></script>

</body>

</html>

main.js

var posOptions =     { enableHighAccuracy: false,
    maximumAge: 0,
    timeout: 5000
};

/**  * Get the current location of the user  */
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showLocation, handleError, posOptions);
    } else {
        console.log ('Not supported');
    }
}

/**  * Show current location coords of the user  *
 *  @param position object with position info  */
function showLocation(position) {
    console.log(position.coords.latitude, position.coords.longitude );
}

function handleError(error) {
    console.log(error.code, error.message );
}



getLocation();

var marker;
var map;
var namemarker;
var API_KEY = "MY_KEY";
var mapScript = document.createElement('script');
mapScript.setAttribute('src', 'https://maps.googleapis.com/maps/api/js?key='+API_KEY+'&callback=initMap' );
mapScript.setAttribute('async', '' );
mapScript.setAttribute('defer', '' );
document.querySelector('body').appendChild(mapScript);
function initMap() {
    navigator.geolocation.getCurrentPosition(showMap, handleError);
}

var divMap = document.querySelector(".divmap");
function showMap(pos) {
    divMap.style.width = '500px';
    divMap.style.height = '500px';
    map = new google.maps.Map(divMap, {
        center:{
            lat: pos.coords.latitude,
            lng: pos.coords.longitude,
        },
        zoom: 16
    });

    marker = new google.maps.Marker({
        position: {
            lat: pos.coords.latitude,
            lng: pos.coords.longitude,},
        map:map,
        title:namemarker,
    });

}

var search = document.querySelector('#search');

search.addEventListener("click", function (ev) {
    ev.preventDefault();
    showPlace();
},false);

function showPlace() {
    var loc = document.querySelector('#place');
    namemarker = document.querySelector('#namemarker');
    console.log(loc.value);

    var reqUrl = "https://maps.googleapis.com/maps/api/geocode/json?address="+loc.value+"&key="+API_KEY;

    fetch(reqUrl)
        .then(function(response) {
            return response.json();
        })
        .then(function (locJson) {
            console.log(locJson);
            var pos = locJson.results[0].geometry.location;

            map.panTo(pos);
            marker.setPosition(pos);
        });
}


I hope someone can help me, thank you in advance for the help!

@RicoPapillon You can add the following line right after the existing marker.setPosition(pos); line in the second then's callback function:

marker.setTitle(namemarker.value);
1 Like

Thank you very much! :smile: