Спасибо за любую помощь, которую вы можете предоставить!
Резюме У меня есть картографическое приложение Google Maps API V2, созданное на Ruby on Rails, и я пытаюсь преобразовать его в V3. Я обновил свой существующий javascript, используя советы из Советы по обновлению Gmaps с v2 на v3 быстрее. Однако мои карты по-прежнему не отображаются на странице.
Подробности. При использовании версии 2 этот код будет отображать серию уникальных карт точек от А до точек Б на одной веб-странице. У пользователя может быть много сохраненных карт, и этот код покажет их. Теперь холст карты и маршрут не разрешаются.
Опять же, я ценю вашу помощь!
РЕДАКТИРОВАТЬ 3: Проблема заключается в calcRoute()
Я посмотрел на все и понял, что карта работает, пока я не начну добавлять переменные Start и End. Эти переменные выглядят так, как будто они должны работать, но направления и маршрут не отображаются. Есть ли что-то, что я делаю неправильно при загрузке этих переменных? Я предоставил как свой оригинальный js, так и результат.
Оригинал:
function calcRoute() {
var start = <%= savedmap.from %>;
var end = <%= savedmap.to %>;
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
Результат:
function calcRoute() {
var start = 4400 Massachusetts Ave NW Washington, District of Columbia, 20016-8001;
var end = 2121 I Street- NW Washington, District of Columbia, 20052;
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
EDIT 2: Результат опубликован
В соответствии с запросом, вот результат того, что происходит, когда я использую скрипт, указанный в EDIT 1.
<head>
<script src="https://maps.googleapis.com/maps/api/js?key=MYKEY&sensor=false"></script>
<script type="text/javascript">
var directionsDisplay7656;
var directionsService7656 = new google.maps.DirectionsService();
var map7656;
function initialize() {
directionsDisplay7656 = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: chicago
}
map7656 = new google.maps.Map(document.getElementById("map_canvas7656"), mapOptions);
directionsDisplay7656.setMap(map7656);
}
function calcRoute() {
var start = 350 5th Ave New York, NY 10118;
var end = 2 Lincoln Memorial Cir Washington, DC 20037;
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService7656.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay7656.setDirections(response);
}
});
}
</script>
</head>
<body id="itineraries"
onload="initialize()">
<input id="auth_token" class="hidden" name="" type="hidden" value="VALUEHERE=" />
<div class="wholemap">
<h4>test</h4>
<div class="map" id="map_canvas7656"></div>
<div class="route" id="route7656"></div>
<div class="clear"></div>
<a id="print7656" target="_blank" class="printmap">Print this map</a>
<a class="removemap" href="/savedmaps/7656">Delete this map</a>
<div class="clear"></div>
</div>
</body
РЕДАКТИРОВАНИЕ 1: вторая попытка
На этот раз я начал с примера Directions от Google. Все равно не повезло, к сожалению.
<script src="https://maps.googleapis.com/maps/api/js?key=MYKEY&sensor=false"></script>
<script type="text/javascript">
<% for savedmap in @maps %>
var directionsDisplay<%= savedmap.id %>;
var directionsService<%= savedmap.id %> = new google.maps.DirectionsService();
var map<%= savedmap.id %>;
function initialize() {
directionsDisplay<%= savedmap.id %> = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: chicago
}
map<%= savedmap.id %> = new google.maps.Map(document.getElementById("map_canvas<%= savedmap.id %>"), mapOptions);
directionsDisplay<%= savedmap.id %>.setMap(map<%= savedmap.id %>);
}
function calcRoute() {
var start = <%= savedmap.from%>;
var end = <%= savedmap.to %>;
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService<%= savedmap.id %>.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay<%= savedmap.id %>.setDirections(response);
}
});
}
<% end %>
</script>
ВЫШЕ ПОСЛЕДНЯЯ ВЕРСИЯ. ИСХОДНЫЙ КОД ПОСЛЕДУЮЩИЙ
JavaScript:
<script src="https://maps.googleapis.com/maps/api/js?key=MYKEY&sensor=false"></script>
<script type="text/javascript">
<% for savedmap in @maps %>
var map<%= savedmap.id %>;
var resultx<%= savedmap.id %>;
var directionsPanel<%= savedmap.id %>;
var directions<%= savedmap.id %>;
<% end %>
function initialize() {
var marker = new google.maps.marker(new google.maps.LatLng(-30.368374, -71.089182)); //initialize a marker out in the middle of nowhere
google.maps.event.addListener(marker, 'click', function() {
});
<% for savedmap in @maps %>
map<%= savedmap.id %> = new google.maps.Map(document.getElementById("map_canvas<%= savedmap.id %>"));
map<%= savedmap.id %>.setCenter(new google.maps.LatLng(42.351505,-71.094455), 15);
directionsPanel<%= savedmap.id %> = document.getElementById("route<%= savedmap.id %>");
directions<%= savedmap.id %> = new google.maps.directions(map<%= savedmap.id %>, directionsPanel<%= savedmap.id %>);
directions<%= savedmap.id %>.load("from: <%= savedmap.from %> to: <%= savedmap.to %>");
//google.maps.event.addListener(directions<%= savedmap.id %>, "error", handleErrors);
map<%= savedmap.id %>.addOverlay(marker);
map<%= savedmap.id %>.addControl(new google.maps.SmallMapControl());
map<%= savedmap.id %>.addControl(new google.maps.MapTypeControl());
$('a#print<%= savedmap.id %>').attr('href', 'http://maps.google.com/maps?f=q&q=from: <%= savedmap.from %> to: <%= savedmap.to %>&t=h&z=13&layer=c&pw=2')
<% end %>
}
/*function handleErrors(){
if (directions<%= savedmap.id %>.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + directions<%= savedmap.id %>.getStatus().code);
else if (directions<%= savedmap.id %>.getStatus().code == G_GEO_SERVER_ERROR)
alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + directions<%= savedmap.id %>.getStatus().code);
else if (directions<%= savedmap.id %>.getStatus().code == G_GEO_MISSING_QUERY)
alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
// else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS) <--- Doc bug... this is either not defined, or Doc is wrong
// alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
else if (directions<%= savedmap.id %>.getStatus().code == G_GEO_BAD_KEY)
alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + directions<%= savedmap.id %>.getStatus().code);
else if (directions<%= savedmap.id %>.getStatus().code == G_GEO_BAD_REQUEST)
alert("A directions request could not be successfully parsed.\n Error code: " + directions<%= savedmap.id %>.getStatus().code);
else alert("An unknown error occurred.");
} */
</script>
Код Maps.html.erb
<% for savedmap in @maps %>
<div class="wholemap">
<% if savedmap.name != nil and savedmap.name != '' %>
<h4><%= savedmap.name %></h4>
<% else %>
<h4>Untitled Map</h4>
<% end %>
<a class="directions" href="#">Show Driving Directions</a>
<div class="clear"></div>
<div class="map" id="map_canvas<%= savedmap.id %>"></div>
<div class="route" id="route<%= savedmap.id %>"></div>
<div class="clear"></div>
<a id="print<%= savedmap.id %>" target="_blank" class="printmap">Print this map</a>
<a class="removemap" href="/savedmaps/<%= savedmap.id %>">Delete this map</a>
<div class="clear"></div>
</div>
<% end %>
Вы еще не добавили карты для этой поездки.