Adding clickablility to LI elements that are dynamically added to web page - javascript

The code I have so far is using the Google Maps API to take in something the user enters, looks it up on the map, and then appends search they entered to the right of the map. The one part I am missing is that for the searches on the right, I have to make them be able to be clicked and upon click they go to the marker on the map. I was wondering if anyone had any advice or hints to help me figure it out, since I have tried a lot of different things (for some reason using the .on('click',...) wouldn't work properly).
Thank you!
.html file:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src = "project2.js"></script>
<link rel = "stylesheet" type = "text/css" href = "project2.css">
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
</head>
<body>
<form>
<div>
<label> Address: </label>
<input id = "address" type = "text">
<input id = "submit" type = "button" value = "Add">
<br><br>
</div>
</form>
<section>
<ul>
</ul>
</section>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAGysAFeYIRV2qqMeEcnehH9igIaSYxvvs&callback=initMap"></script>
</body>
</html>
.js file:
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 41.083, lng: -74.174},
zoom: 8
});
var geocoder = new google.maps.Geocoder();
document.getElementById('submit').addEventListener('click', function() {
showAddress(geocoder, map);
//getLinks();
});
}
function showAddress(geocoder, newMap)
{
var address = document.getElementById('address').value;
//console.log(address);
$('<li/>').addClass('list').text(address).appendTo('ul');
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
newMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map:newMap,
position: results[0].geometry.location
});
}
else {
alert('Geocode was not successful for reason: ' + status);
}
});
}
/*
function getLinks()
{
console.log("hey");
$('#elements').on('click', 'li', function(){
alert($(this).text());
console.log("hey2");
});
}*/
.css file:
input[type = text]
{
width: 375px;
}
li {
list-style-type: none;
width: 450px;
border-style: solid;
padding: 0.3em;
margin-left: 475px;
margin-right: auto;
margin-bottom: .5em;
}
.list {
background-color: #8E8989;
}
#map {
position:absolute;
top: 50px;
height:60%;
width:40%;
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
}
html, body{
height: 100%;
margin:0;
padding:5px;
}
Thank you!

I would suggest adding an id to the <ul>, and attach a click event listener to it instead of the dynamically created <li>.
For example:
<ul id="address-list">
Then in javascript, use:
$("#address-list").on("click",".list",function(){
/* Do something */
})

To add event on dynamically generated elements you need to use something like
$('body').on('click', 'li', function() { // do something });

Related

How to change language in mapbox

I need to change the language of the mapbox in javascript, I only see the below code in the documentation
map.setLayoutProperty('country-label', 'text-field', ['get', 'name_de'])
but this line of code will only change the country names but I need everything ( city, town, ...etc)
Based on your mapbox style, there will be different text layers. For dark-v9, these are the available text layers.
country-label
state-label
settlement-label
settlement-subdivision-label
airport-label
poi-label
water-point-label
water-line-label
natural-point-label
natural-line-label
waterway-label
road-label
Using the code snippet that you mentioned in the question on the above layers, you should be able to change the language.
map.setLayoutProperty('country-label', 'text-field', ['get', 'name_de'])
Or you can use mapbox-language-plugin to change the language of all the possible layers. Here is the working example of the plugin.
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Change a map's language</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v1.4.1/mapbox-gl.js'></script>
<script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-language/v0.10.1/mapbox-gl-language.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v1.4.1/mapbox-gl.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<style>
#buttons {
width: 90%;
margin: 0 auto;
}
.button {
display: inline-block;
position: relative;
cursor: pointer;
width: 20%;
padding: 8px;
border-radius: 3px;
margin-top: 10px;
font-size: 12px;
text-align: center;
color: #fff;
background: #ee8a65;
font-family: sans-serif;
font-weight: bold;
}
</style>
<div id='map'></div>
<ul id="buttons">
<li id='button-fr' class='button'>French</li>
<li id='button-ru' class='button'>Russian</li>
<li id='button-de' class='button'>German</li>
<li id='button-es' class='button'>Spanish</li>
</ul>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoibXVyYWxpcHJhamFwYXRpIiwiYSI6ImNrMHA1d3VjYzBna3gzbG50ZjR5b2Zkb20ifQ.guBaIUcqkTdYHX1R6CM6FQ';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/dark-v9',
center: [16.05, 48],
zoom: 2.9
});
mapboxgl.setRTLTextPlugin('https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.1.0/mapbox-gl-rtl-text.js');
var mapboxLanguage = new MapboxLanguage({
defaultLanguage: 'en'
});
map.addControl(mapboxLanguage);
document.getElementById('buttons').addEventListener('click', function(event) {
var language = event.target.id.substr('button-'.length);
map.setStyle(mapboxLanguage.setLanguage(map.getStyle(), language));
});
</script>
</body>
</html>
Ref: https://blog.mapbox.com/how-to-localize-your-maps-in-mapbox-gl-js-da4cc6749f47
Here is a code I have found helpful for me from github mapbox here
map.getStyle().layers.forEach(function(thisLayer){
if(thisLayer.type == 'symbol'){
map.setLayoutProperty(thisLayer.id, 'text-field', ['get','name_ja'])
}
})
I have modified it to
map.getStyle().layers.forEach(function(thisLayer){
console.log(thisLayer);
if(thisLayer.id.indexOf('-label')>0){
console.log('change '+thisLayer.id);
map.setLayoutProperty(thisLayer.id, 'text-field', ['get','name_fr'])
}
});
But otherwise you'll have to change the different labels yourself as mentionned by murli-prajapati
Of course, change 'name_xx' by your own language
such as:
map.setLayoutProperty('country-label', 'text-field', ['get','name_fr']);
map.setLayoutProperty('state-label', 'text-field', ['get','name_fr']);
map.setLayoutProperty('settlement-label', 'text-field', ['get','name_fr']);
map.setLayoutProperty('settlement-subdivision-label', 'text-field', ['get','name_fr']);
The only thing that helped me is a cycle placed in load event:
map.on('load', function() {
let labels = [ 'country-label', 'state-label',
'settlement-label', 'settlement-subdivision-label',
'airport-label', 'poi-label', 'water-point-label',
'water-line-label', 'natural-point-label',
'natural-line-label', 'waterway-label', 'road-label' ];
labels.forEach(label => {
map.setLayoutProperty(label, 'text-field', 'get','name_ru']);
});
})
Language plugin and other stuff didn't work.
Belatedly, you could use this plugin to change the display language according to the user locale.
https://github.com/mapbox/mapbox-gl-language
For example:
mapboxgl.accessToken = 'YOUR_ACCESS_TOKEN';
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v10',
center: [-77.0259, 38.9010],
zoom: 9
});
const language = new MapboxLanguage();
map.addControl(language);
After trying all the solutions in this thread with streets-v12 I found non of them gave me what I needed.
The plug-in doesn’t work at all, and #Mike & #honey59 solutions semi-work, I still found many components not translated.
What did work best for me was to use Mapbox’s studio to create custom map and change the language there to all the components & layers (guide: https://docs.mapbox.com/help/troubleshooting/change-language/).
And on my site I know when user is viewing the page on a specific language, so I just needed to map the languages to their custom maps URLs.
I know it’s not the most “technical” dynamic solution, but I found it to be the most complete one

Google map API is not displaying my map even though I have the correct authentication key

Google API map not displaying when I load my code in a google chrome browser. I created my authentication key with in a new project on the Google Cloud Platform.
I've tried generating a new authentication key on the Google Cloud platform by creating a new project, but that did not seemed to work.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
#map{
height:100%;
}
</style>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="output">Complete JavaScript Course </div>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?
key=<<my key>>"></script>
<script src="app.js">
window.onload = init;
var m = document.getElementById('map');
function init() {
navigator.geolocation.getCurrentPosition(placeMap);
}
function placeMap(data) {
var options = {
center: {
lat: data.coords.latitude
, lng: data.coords.longitude
}
, zoom: 5
}
var map = new google.maps.Map(m, options);
console.dir(data);
}
</script>
</body>
</html>
As I've already stated, the google map api will not display a map of my actual location.
You have two issues with the posted code.
Your map div doesn't have a size, you need to define the size of html and body so the #map 100% height has something to reference:
<style>
#map{
height:100%;
}
</style>
should be:
<style>
html, body, #map {
height: 100%;
margin: 0;
padding: 0;
}
</style>
you have an unneeded src on your script tag:
<script src="app.js">
should be:
<script>
proof of concept fiddle
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 90%;
}
<div id="output">Complete JavaScript Course </div>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script>
window.onload = init;
var m = document.getElementById('map');
function init() {
navigator.geolocation.getCurrentPosition(placeMap);
}
function placeMap(data) {
var options = {
center: {
lat: data.coords.latitude,
lng: data.coords.longitude
},
zoom: 5
}
var map = new google.maps.Map(m, options);
console.dir(data);
}
</script>
You need to access the API using the callback after google maps have already been loaded. This is done by passing in a parameter to google maps initialization by passing in callback as a query parameter. You also need to activate your api to have Javascript functionality
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map;
function initMap(position) {
map = new google.maps.Map(document.getElementById('map'), {
center: position,
zoom: 8
});
}
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
initMap({
lng: position.coords.longitude, lat: position.coords.latitude});
});
} else {
initMap({lat: -34.397, lng: 150.644});
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCD9OuD6hAbRm5JNSEpkCTE6HzhaOp5uCc&callback=getLocation"
async defer></script>
</body>
</html>

Google Maps API not showing at all using HTML5

For the first time I'm trying to incorporate the Google Maps API into a website and it's not working at all. I can't tell if there's something wrong with the code and I'd like to rule that out before trying to create another API Key
I've moved the tag around and tried different styling approaches, but it just doesn't show anything.
<!DOCTYPE html>
<html>
<head>
<script>
function initMap() {
var location = { lat: -30.0327268, lng: -51.2095745 };
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 4,
center: location
});
}
</script>
<script async defer
src="https://maps.googleapis/maps/api/js?key=AIzaSyBDXh6FfycwxdCaHUbrCWkswSarA77kowY&callback=initMap">
</script>
<title>
</title>
<style>
* {
margin: 0;
padding: 0;
}
#map {
height: 500px;
width: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
</body>
</html>
The URL in the script that you are using is incorrect.
You are using: https://maps.googleapis/maps/api/js?key=AIzaSyBDXh6FfycwxdCaHUbrCWkswSarA77kowY&callback=initMap
The correct URL: https://maps.googleapis.com/maps/api/js?key=AIzaSyBDXh6FfycwxdCaHUbrCWkswSarA77kowY&callback=initMap
Hope this helps!
The below line was not added correctly,
It should be in this form
Below is the updated code in which map is working fine..
<!DOCTYPE html>
<html>
<head>
<script>
function initMap() {
var location = { lat: -30.0327268, lng: -51.2095745 };
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 4,
center: location
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBDXh6FfycwxdCaHUbrCWkswSarA77kowY&callback=initMap"
async defer></script>
<title>
</title>
<style>
* {
margin: 0;
padding: 0;
}
#map {
height: 500px;
width: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
</body>
</html>

Problems implementing Google Maps API (for Business)

This should be pretty basic but I cant really find the answer to it:
I try to implement a Google map, using the Google API for business and got a working client ID / key.
Using the standard examples from for the documentation (https://developers.google.com/maps/documentation/javascript/tutorial) its only possible to get a blank map.
This is the simple test code that show a blank map:
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I need to get the correct map with all the info and places that its containing.
All the examples I find are for getting a blank map, or adding stuff to it.
Thanks,
/b
Your supplied JavaScript works for me. Have you included the required div in your webpage?
<div id="map-canvas"/>
Plus the div may need to be styled, as the map may be there but with 0px height and 0px width (hence making it impossible to see), the following CSS will make your div fullscreen:
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
So, overall, you should have this:
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=API_KEY">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"/>
</body>
</html>

Using Google Maps to make multiple markers on address input and button click

I've looked at similar questions and can't quite figure this out, though I think I'm close.
The goal is to have a form which allows address input, and upon submit button click the address should be added as a marker on the already loaded map.
I've got garbled sample code all over the place, but here is what I've been working with(refactored from a Laravel 4 view):
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key="> // Placeholder API Key
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(29.428459, -98.492433), // Centered on downtown SA by default
zoom: 11
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<br>
<div id="user-input-form" style="width: 500px; height: 200px; margin-left: 20px;">
<input id="user-input" class="form-group form-control" name="user-input" type="text" value="112 E. Pecan St San Antonio TX 78205" placeholder="">
<button id="user-input-btn" class="btn btn-default" action="">Submit</button>
<p id="address-text"></p>
</div>
</div>
<div id="map-canvas" style="width: 500px; height: 400px;"></div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script type="text/javascript">
function addMarker() { // Function to add markers on button click
var marker = new google.maps.Marker({
position: latlng, // set to location which corresponds with user input? Don't want to recenter map each time.
map: map,
draggable:false,
animation: google.maps.Animation.DROP,
title:"Marker #",
icon: "http://maps.google.com/mapfiles/ms/micons/blue.png"
});
}
$('#user-input-btn').click(function () {
var address = $('#user-input').val(); // Grab value of input field above
console.log(address);
$('#address-text').text('You entered: ' + address);
$('#address').text(address);
// Call addMarker function?
}); // end event from button click
</script>
</body>
</html>
Can anyone help me step through this? I'm trying to do something more complicated, but being able to:
Add markers via address submit through a form/button click.
Reset the map with a reset button to clear all the overlays.
Would be an awesome step forward.
Thank you
Okay thanks to kinakuta I was able to outline the following and implement it:
<script type="text/javascript">
$('#addr-btn').click(function () {
// Set variable address equal to user input
var address = $('#addr-value').val();
// Geocode address to get lat/lng
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function(result, status) {
if (status == google.maps.GeocoderStatus.OK) {
// console.log(result);
var latLngObj = result[0]["geometry"]["location"];
console.log(latLngObj);
}
// Create new marker based on lat/lng
var marker = new google.maps.Marker({
position: latLngObj,
map: map,
title:"Hello World!"
});
// Store marker in array to keep all markers on the page, and allow easy reset
});
});
</script>
Thanks!

Categories

Resources