Reputation: 57
So i am using the Google maps API for my website and I want the markers text to be equal to the value of another html element. Anyone here knows how to update the value of the text property of a marker in the google maps API?
Here is my code regarding the problem.
var map, marker;
var input = document.getElementById('inputField');
input.onkeyup = function() {
//want to set the marker.text property to input.value and update the markers text
}
function myMap() {
var long = 59.614503;
var lat = 16.539939;
var myLatlng = new google.maps.LatLng(lat, long);
var mapProp = {
center: new google.maps.LatLng(long, lat),
zoom: 16,
styles: [......]
}
}
map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
marker = new google.maps.Marker({
position: new google.maps.LatLng(long, lat),
label: {
color: 'white',
fontWeight: 'bold',
fontSize: '10px',
text: arena
},
optimized: false,
visible: true,
draggable: true,
});
marker.setMap(map);
Upvotes: 3
Views: 4463
Reputation: 161324
Get the existing label object, set its text
property to the desired value, then set it on the marker (unless you want to change other formatting).
input.onkeyup = function() {
var label = marker.getLabel();
label.text = input.value;
marker.setLabel(label);
}
code snippet:
var map, marker;
function initialize() {
var input = document.getElementById('inputField');
input.onkeyup = function() {
var label = marker.getLabel();
console.log(label);
label.text = input.value;
marker.setLabel(label);
}
function myMap() {
var lat = 59.614503;
var lng = 16.539939;
var myLatlng = new google.maps.LatLng(lat, lng);
var mapProp = {
center: new google.maps.LatLng(lat, lng),
zoom: 16
}
map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
label: {
color: 'white',
fontWeight: 'bold',
fontSize: '10px',
text: "arena"
},
optimized: false,
visible: true,
draggable: true,
});
marker.setMap(map);
}
myMap();
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#googleMap {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<input id="inputField" />
<div id="googleMap"></div>
Upvotes: 4
Reputation: 133360
You coul try using
marker.label.text = 'my_new_text'; // set the new text
marker.label..setStyles(); // Force label to redraw (makes update visible)
Upvotes: 1