Tengo un archivo html y js. Estoy tratando de probar los mapas de Google con javascript. Quiero poder agregar dinámicamente posiciones en la selección. Por alguna razón, el signo # no funciona. Estoy seguro de que es algo fácil, solo me estoy perdiendo.
Cuando uso este código ...
$('start').append('<option value="foo" selected="selected">Foo</option>');
¿Por qué es la salida ...
"<option value="foo" selected="selected">Foo</option>"
Muestra comillas dobles y no se muestra como HTML.
Html
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<div id="formAdd">
<h1>Add Site</h1>
<label for="name">Name:</label>
<input type="text" id="name"><br>
</div>
<br/><br/>
<div id="floating-panel">
<b>Start: </b>
<select id="start">
</select>
<b>End: </b>
<select id="end">
</select>
</div>
<br/><br/>
<div id="googleMap" style="width:50%;height:400px;float:left"></div>
<div id="parent" style="float: left">
<ul id="list">
</ul>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=&callback=myMap"></script>
<script src="map.js"></script>
</body>
Aquí está mi archivo JS
var positions = [];
var names = [];
var $ = function (id) {
return document.getElementById(id);
}
window.onload = function () {
initMap();
}
function getCurrentLocation(callback) {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
callback(new google.maps.LatLng(position.coords.latitude,position.coords.longitude));
});
}
else {
throw new Error("Your browser does not support geolocation.");
}
}
function initMap() {
//Create new map in googleMap div
map = new google.maps.Map($("googleMap"), {
zoom: 10
});
//Get the current location
geoLocation(map);
//Map clicked, create marker
map.addListener('click', function(e) {
createMarker(e.latLng, map);
for (var i = 1; i <= positions.length-1; i++) {
$("start").append('<option value="(40.23277990064058, -75.04673282753907)">Test</option>');
}
});
}
function createMarker(latLng, map) {
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: $("name").value
});
//alert(marker.position);
positions[positions.length] = marker.position;
names[names.length] = marker.title;
}
3 respuestas
Este código va a ser ligeramente diferente al tuyo porque fui y creé esto desde cero y puse partes relevantes de tu código. Pero espero que esto ayude. Mi código ahora está insertando opciones de selección para los clics (cuando se proporciona un nombre en el campo de entrada).
var positions = [];
var names = [];
var map, infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('googleMap'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
//Map clicked, create marker
map.addListener('click', function(e) {
createMarker(e.latLng, map);
var start = document.getElementById("start");
var locationName = document.getElementById("name").value;
start.options[start.options.length] = new Option(locationName, '40.23277990064058, -75.04673282753907');
});
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
function createMarker(latLng, map) {
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: document.getElementById("name").value
});
//alert(marker.position);
positions[positions.length] = marker.position;
names[names.length] = marker.title;
}
Observe que eliminé la referencia de jquery y utilicé vanilla javascript para seleccionar elementos. Esto se debía a que el '#' le estaba causando problemas anteriormente (y los documentos de Google estaban usando vanilla js, así que también tomé esa ruta). Espero que esto ayude, pero avíseme si esto no cubre lo que necesita.
-Además, he codificado los datos de ubicación, probablemente querrás recuperarlos dinámicamente una vez que lo hagas funcionar.
En primer lugar, debe usar #start
para el selector de ID. En segundo lugar, funciona bien:
$('#start').append('<option value="foo" selected="selected">Foo</option>');
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<select id="start"></select>
Hola, soy nuevo en esto y no estoy completamente seguro de si esto es correcto, pero tal vez puedas probar este código
$("#start").append("<option value='"+(40.23277990064058, -75.04673282753907)+"'>Test</option>");
Acabo de poner # y algunas comillas
Preguntas relacionadas
Nuevas preguntas
javascript
Para preguntas sobre la programación en ECMAScript (JavaScript / JS) y sus diversos dialectos / implementaciones (excepto ActionScript). Incluya todas las etiquetas relevantes en su pregunta; por ejemplo, [node.js], [jquery], [json], etc.