IE7 is giving me an issue with a script, using Google Maps API.
When the page is loaded, it says in a alert box 'undefined not found'.
This only happens in IE7, not IE8, nor IE9. Fine in other browsers too, i guess there is a coding error. As soon as i take out JS, no warning but map doesn't work, obviously.
Here is my entire JS. Thanks in advance!
var map;
var markers = [];
var infoWindow;
var panorama;
function init_map() {
map = new google.maps.Map(document.getElementById("map"), {
//center: new google.maps.LatLng(40, -100),
zoom: 4,
mapTypeId: 'roadmap',
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
});
infoWindow = new google.maps.InfoWindow();
var address = $('#address').val();
var address_optional = $('#address_optional').val();
if (address == '' && address_optional != '1') init_location();
else searchLocations(address_optional);
}
function init_location(lat, lng, zoom) {
if (lat === undefined) lat = 40;
if (lng === undefined) lng = -100;
if (zoom === undefined) zoom = 4;
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(lat, lng),
zoom: zoom,
mapTypeId: 'roadmap',
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
});
}
$("#next").live('click', function(event) {
event.preventDefault();
var page_number = $('body').data("page_number");
$('body').data("page_number", (page_number + 1));
searchLocations();
});
$("#previous").live('click', function(event) {
event.preventDefault();
var page_number = $('body').data("page_number");
$('body').data("page_number", (page_number - 1));
searchLocations();
});
function searchLocations() {
var address = $('#address').val();
var geocoder = new google.maps.Geocoder();
var address_optional = $('#address_optional').val();
geocoder.geocode({
address: address
}, function(results, status) {
if ((status == google.maps.GeocoderStatus.OK)) {
searchLocationsNear(results[0].geometry.location);
} else {
if (address_optional == '1') {
searchLocationsNear('', 1);
} else {
alert(address + ' not found');
}
}
});
}
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
var option = document.createElement("option");
option.value = "none";
option.innerHTML = "See all results:";
}
function createSidebarEntry(markerNum, sidebarContent, markerContent, lat, lng) {
var div = document.createElement('div');
div.innerHTML = sidebarContent;
div.style.cursor = 'pointer';
div.style.marginBottom = '5px';
div.onclick = function() {
infoWindow.setContent(markerContent);
infoWindow.open(map, markers[markerNum]);
init_location(lat, lng, 16);
var latlng = new google.maps.LatLng(
parseFloat(lat), parseFloat(lng));
createMarker(latlng, lat, lng, markerContent);
}
return div;
}
function resizeMap(width, height) {
$('#map').animate({
width: width,
height: height
}, function() {
google.maps.event.trigger(map, 'resize');
map.setCenter(map.getCenter());
});
}
function streetView(lat, lng) {
var dom = 'streetview';
panorama = new google.maps.StreetViewPanorama(document.getElementById(dom));
displayStreetView(lat, lng, dom);
if ($('#map').height() == 600) {
resizeMap(850, 300);
$('#streetview').height(300);
}
}
function searchLocationsNear(center, address_optional) {
clearLocations();
var sidebar = document.getElementById('sidebar');
sidebar.innerHTML = '';
var page_number = $('body').data("page_number");
if (page_number == null) {
page_number = 1;
$('body').data("page_number", page_number);
}
var categoryid = $('#categoryid').val();
if (address_optional == '1') var searchUrl = 'map_data.php?categoryid=' + categoryid + '&page_number=' + page_number + '&address_optional=' + address_optional;
else var searchUrl = 'map_data.php?lat=' + center.lat() + '&lng=' + center.lng() + '&categoryid=' + categoryid + '&page_number=' + page_number;
//alert(searchUrl);
$.ajax({
type: 'GET',
url: searchUrl,
dataType: 'json',
success: function(msg) {
var locations = msg.locations;
var markersContent = msg.markersContent;
var sidebarContent = msg.sidebarContent;
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < locations.length; i++) {
var name = locations[i]['name'];
var address = locations[i]['address'];
var distance = parseFloat(locations[i]['distance']);
var latlng = new google.maps.LatLng(
parseFloat(locations[i]['lat']), parseFloat(locations[i]['lng']));
var sidebarEntry = createSidebarEntry(i, sidebarContent[i], markersContent[i], locations[i]['lat'], locations[i]['lng']);
sidebar.appendChild(sidebarEntry);
createOption(name, distance, i);
createMarker(latlng, locations[i]['lat'], locations[i]['lng'], markersContent[i]);
bounds.extend(latlng);
}
$('#pagination').html(msg.pagination);
map.fitBounds(bounds);
}
});
resizeMap(850, 600);
$('#streetview').html('').height(0);
}
function createMarker(latlng, lat, lng, html) {
var marker = new google.maps.Marker({
map: map,
position: latlng,
animation: google.maps.Animation.DROP
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, this);
});
$("#sidebar div").click(function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
markers.push(marker);
}
function createOption(name, distance, num) {
var option = document.createElement("option");
option.value = num;
option.innerHTML = name + "(" + distance.toFixed(1) + ")";
}
function displayStreetView(lat, lng, dom) {
var latlng = new google.maps.LatLng(lat, lng);
var panoramaOptions = {
position: latlng,
pov: {
heading: 270,
pitch: 0,
zoom: 1
}
};
panorama = new google.maps.StreetViewPanorama(document.getElementById(dom), panoramaOptions);
map.setStreetView(panorama);
}
Related
Firstly, I have been checking all over the web but I couldnt find an answer.
I combined autocomplete with goole maps and if a user wants, he/she can move the marker as well and I get address from it. You can find the code below.
When a user searches for instance Nice, France, is it possible to fit Nice from e.g borders to my map? Maybe I have to change the zoom dynamically or I need to set new viewport, I am not sure. So far what I found is, I can give a distance and create a circle to fit that circle to the viewport. But circle's radius is set, so it can fit to Nice but can not fit to Miami.
Hope I could explain what I mean. Thank you in advance.
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
#map_canvas {
width: 980px;
height: 500px;
}
#current {
padding-top: 5px;
}
</style>
</head>
<body>
<label>Enter address:</label><br>
<input id="searchTextField" type="text" size="50" style="margin-bottom: 20px;">
<section>
<div id='map_canvas' style=""></div>
<div id="current">No info...</div>
</section>
<div style="margin-top: 10px;" id="data_area">
</div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 10,
center: new google.maps.LatLng(41.0082, 28.9784),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(41.0082, 28.9784),
draggable: true
});
var geocoder = new google.maps.Geocoder;
var markers = [];
markers.push(myMarker);
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
map.addListener('idle', function() {
console.log(map.getBounds());
var bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
});
google.maps.event.addListener(autocomplete, 'place_changed', function () {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
var place = autocomplete.getPlace();
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(place.geometry.location.lat(), place.geometry.location.lng()),
draggable: true
});
markers.push(myMarker);
map.setCenter(myMarker.position);
myMarker.setMap(map);
google.maps.event.clearListeners(myMarker, 'dragend');
google.maps.event.clearListeners(myMarker, 'dragstart');
drag(myMarker, geocoder, map);
});
drag(myMarker, geocoder, map);
map.setCenter(myMarker.position);
myMarker.setMap(map);
}
function drag(myMarker, geocoder, map) {
geocodeLatLng(geocoder, map, myMarker.getPosition().lat(), myMarker.getPosition().lng());
google.maps.event.addListener(myMarker, 'dragend', function (evt) {
document.getElementById('current').innerHTML = '<p>Lat: ' + evt.latLng.lat().toFixed(3) + ' Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
geocodeLatLng(geocoder, map, evt.latLng.lat(), evt.latLng.lng());
});
google.maps.event.addListener(myMarker, 'dragstart', function (evt) {
document.getElementById('current').innerHTML = '<p>Waiting...</p>';
});
}
function geocodeLatLng(geocoder, map, lat, lng) {
var input = lat + "," + lng;
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
console.log(results[0])
var data_arr = []
document.getElementById("data_area").innerHTML = "";
var data_country = results[0].address_components.find(function(element) {
return element.types[0] == "country";
});
var data_administrative_1 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_1";
});
var data_administrative_2 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_2";
});
var data_administrative_3 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_3";
});
var data_administrative_4 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_4";
});
var data_route = results[0].address_components.find(function(element) {
return element.types[0] == "route";
});
if (data_route !== undefined) {data_arr.push(data_route["long_name"]);}
if (data_administrative_4 !== undefined) {data_arr.push(data_administrative_4["long_name"]);}
if (data_administrative_3 !== undefined) {data_arr.push(data_administrative_3["long_name"]);}
if (data_administrative_2 !== undefined) {data_arr.push(data_administrative_2["long_name"]);}
if (data_administrative_1 !== undefined) {data_arr.push(data_administrative_1["long_name"]);}
if (data_country !== undefined) {data_arr.push(data_country["long_name"]);}
data_arr.forEach(function(data) {
var node = document.createElement("LI");
var textnode = document.createTextNode(data);
node.appendChild(textnode);
document.getElementById("data_area").appendChild(node);
});
} else {
window.alert('No data!');
}
} else {
window.alert('Geocoder failed: ' + status);
}
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?libraries=places&key=MY_API_KEY&callback=initMap"></script>
</body>
</html>
The Autocomplete service returns the geometry of the location selected, zoom the map to show those bounds (in the fiddle/snippet I added a rectangle to show the bounds returned, if you don't want that displayed, remove it):
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else if (place.geometry.bounds) {
map.fitBounds(place.geometry.bounds);
}
proof of concept fiddle
html,
body {
height: 100%;
width: 100%;
padding: 0px;
margin: 0px;
}
#map_canvas {
width: 100%;
height: 80%;
}
#current {
padding-top: 5px;
}
<label>Enter address:</label><br>
<input id="searchTextField" type="text" size="50" style="margin-bottom: 20px;">
<section style="width: 100%; height:100%;">
<div id='map_canvas' style=""></div>
<div id="current">No info...</div>
</section>
<div style="margin-top: 10px;" id="data_area"></div>
<script>
var rect;
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 10,
center: new google.maps.LatLng(41.0082, 28.9784),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(41.0082, 28.9784),
draggable: true
});
var geocoder = new google.maps.Geocoder;
var markers = [];
markers.push(myMarker);
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
map.addListener('idle', function() {
console.log(map.getBounds());
var bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
if (rect && rect.setMap) rect.setMap(null);
rect = new google.maps.Rectangle({
map: map,
bounds: place.geometry.viewport
})
} else if (place.geometry.bounds) {
map.fitBounds(place.geometry.bounds);
if (rect && rect.setMap) rect.setMap(null);
rect = new google.maps.Rectangle({
map: map,
bounds: place.geometry.bounds
})
}
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(place.geometry.location.lat(), place.geometry.location.lng()),
draggable: true
});
markers.push(myMarker);
map.setCenter(myMarker.position);
myMarker.setMap(map);
google.maps.event.clearListeners(myMarker, 'dragend');
google.maps.event.clearListeners(myMarker, 'dragstart');
drag(myMarker, geocoder, map);
});
drag(myMarker, geocoder, map);
map.setCenter(myMarker.position);
myMarker.setMap(map);
}
function drag(myMarker, geocoder, map) {
geocodeLatLng(geocoder, map, myMarker.getPosition().lat(), myMarker.getPosition().lng());
google.maps.event.addListener(myMarker, 'dragend', function(evt) {
document.getElementById('current').innerHTML = '<p>Lat: ' + evt.latLng.lat().toFixed(3) + ' Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
geocodeLatLng(geocoder, map, evt.latLng.lat(), evt.latLng.lng());
});
google.maps.event.addListener(myMarker, 'dragstart', function(evt) {
document.getElementById('current').innerHTML = '<p>Waiting...</p>';
});
}
function geocodeLatLng(geocoder, map, lat, lng) {
var input = lat + "," + lng;
var latlngStr = input.split(',', 2);
var latlng = {
lat: parseFloat(latlngStr[0]),
lng: parseFloat(latlngStr[1])
};
geocoder.geocode({
'location': latlng
}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
console.log(results[0])
var data_arr = []
document.getElementById("data_area").innerHTML = "";
var data_country = results[0].address_components.find(function(element) {
return element.types[0] == "country";
});
var data_administrative_1 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_1";
});
var data_administrative_2 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_2";
});
var data_administrative_3 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_3";
});
var data_administrative_4 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_4";
});
var data_route = results[0].address_components.find(function(element) {
return element.types[0] == "route";
});
if (data_route !== undefined) {
data_arr.push(data_route["long_name"]);
}
if (data_administrative_4 !== undefined) {
data_arr.push(data_administrative_4["long_name"]);
}
if (data_administrative_3 !== undefined) {
data_arr.push(data_administrative_3["long_name"]);
}
if (data_administrative_2 !== undefined) {
data_arr.push(data_administrative_2["long_name"]);
}
if (data_administrative_1 !== undefined) {
data_arr.push(data_administrative_1["long_name"]);
}
if (data_country !== undefined) {
data_arr.push(data_country["long_name"]);
}
data_arr.forEach(function(data) {
var node = document.createElement("LI");
var textnode = document.createTextNode(data);
node.appendChild(textnode);
document.getElementById("data_area").appendChild(node);
});
} else {
window.alert('No data!');
}
} else {
window.alert('Geocoder failed: ' + status);
}
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>
This javascript wont get the coordinates of the user
(this is a html, js and css application only)
(the area with Bold and Italic text, is the one supposed to get the coordinates from the client)
I have tried different soloutions, and they wont work, + it doesnt show the ones if the user is within 25km
center: new google.maps.LatLng(val(coords.latitude),val(coords.longitude)),
<script type="text/javascript">
var side_bar_html = "";
var gmarkers = [];
var map = null;
var markerclusterer = null;
function createMarker(latlng, name, html) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
gmarkers.push(marker);
side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a><br>';
}
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
function initialize() {
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(val(coords.latitude),val(coords.longitude)),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
google.maps.event.addListener(map, 'click', find_closest_marker);
downloadUrl("markers.xml", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var id = markers[i].getAttribute("id");
var sted = markers[i].getAttribute("sted");
var html="<b>"+sted+"</b><br>"+id;
var marker = createMarker(point,sted+" "+id,html);
}
markerCluster = new MarkerClusterer(map, gmarkers);
document.getElementById("side_bar").innerHTML = side_bar_html;
});
}
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
function find_closest_marker( event ) {
var closestMarker = -1;
var closestDistance = Number.MAX_VALUE;
for( i=0;i<gmarkers.length; i++ ) {
var distance = google.maps.geometry.spherical.computeDistanceBetween(gmarkers[i].getPosition(),event.latLng);
if ( distance < closestDistance ) {
closestMarker = i;
closestDistance = distance;
}
}
map.setCenter(gmarkers[closestMarker].getPosition());
if (map.getZoom() < 16) map.setZoom(16);
google.maps.event.trigger(gmarkers[closestMarker], 'click');
}
</script>
You can user a simple JS function for that.
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showLatLng);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showLatLng(location) {
alert("Latitude: " + location.coords.latitude +
"Longitude: " + location.coords.longitude);
}
</script>
Hope it helps
I have a problem, im making a list for the markers on my Google Maps but i want it to make a link that will display the Values of that on the List, it is looped by getJson and the <li> is only appended upon loop.
Can someone help me making it a Link that will alert the values?
This is my sets of codes:
<script type="text/javascript">
var geocoder;
var map;
//var mgr;
function initialize() {
var minZoomLevel = 4;
var zooms = 7;
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map'), {
zoom: minZoomLevel,
center: new google.maps.LatLng(38.50, -90.50),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Bounds for North America
var strictBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(15.70, -160.50),
new google.maps.LatLng(68.85, -55.90)
);
// Listen for the dragend event
google.maps.event.addListener(map, 'dragend', function () {
if (strictBounds.contains(map.getCenter())) return;
// We're out of bounds - Move the map back within the bounds
var c = map.getCenter(),
x = c.lng(),
y = c.lat(),
maxX = strictBounds.getNorthEast().lng(),
maxY = strictBounds.getNorthEast().lat(),
minX = strictBounds.getSouthWest().lng(),
minY = strictBounds.getSouthWest().lat();
if (x < minX) x = minX;
if (x > maxX) x = maxX;
if (y < minY) y = minY;
if (y > maxY) y = maxY;
map.setCenter(new google.maps.LatLng(y, x));
});
// Limit the zoom level
google.maps.event.addListener(map, 'zoom_changed', function () {
if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
});
codeAddress();
}
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
function codeAddress() {
var infowindow = new google.maps.InfoWindow();
$.getJSON('/Dashboard/LoadWorkerList', function (address) {
$.each(address, function () {
var currVal = this["AddressLine1"];
geocoder.geocode({ 'address': currVal }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
icon: iconBase + 'man.png',
position: results[0].geometry.location,
title: currVal
})
$('#places').append($('<li/>')
.text(currVal)
.data('location', results[0].geometry.location));
google.maps.event.addListener(map, 'bounds_changed', function () {
$('#places li').css('display', function () {
return (map.getBounds().contains($(this).data('location')))
? ''
: 'none';
});
});
//mgr = new MarkerManager(map);
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(currVal);
infowindow.open(map, marker);
}
})(marker, currVal));
address.push(marker);
}
else if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(codeAddress, 2000);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
});
google.maps.event.trigger(map, 'bounds_changed');
});
}
window.onload = function () {
initialize();
}
</script>
LoadWorkerList:
public JsonResult LoadWorkerList()
{
var workerList = new List<Worker_Address>();
// check if search string has value
// retrieve list of workers filtered by search criteria
var list = (from a in db.Worker_Address
where a.LogicalDelete == false
select a).ToList();
List<WorkerAddressInfo> wlist = new List<WorkerAddressInfo>();
foreach (var row in list)
{
WorkerAddressInfo ci = new WorkerAddressInfo
{
ID = row.ID,
Worker_ID = row.WorkerID,
AddressLine1 = row.Address_Line1 + " " + row.Address_Line2+ " " +row.City + " "+ GetLookupDisplayValById(row.State_LookID),
LogicalDelete = row.LogicalDelete
};
wlist.Add(ci);
}
return Json(wlist.ToList().OrderBy(p => p.AddressLine1), JsonRequestBehavior.AllowGet);
}
The following line:
$('#places').append($('<li/>')
should be changed. / in front of > should be removed:
$('#places').append($('<li>')
If the list with ID places is available you will get the list of addresses.
I'm using the Google Maps code with PHP MySql, and as per the code from their developers site I've got the map working. However, as part of their code they add a menu (which contains all of the returned options) under the map. The problem is that when i carry out another search I get another added rather than the one that is already there being updated with the new information. I think that the problem is something to dow with the locationSelect object, I would appreciate some help with it:
//Variables that we need later
var map;
var markers = [];
var infoWindow;
var locationSelect;
var myLatLng = new google.maps.LatLng(40,-100);
var addmap = ('<div id="map" style="visibility:visible;"></div>');
var addLocationSelect = '</br><div id="locationSelectDiv"><select id="locationSelect"></select></div>';
var subject_text = "";
var subject_id = "";
function load(myLatlng) {
map = new google.maps.Map(document.getElementById("map"), {
center: myLatLng,
zoom: 3,
mapTypeId: 'roadmap',
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
});
google.maps.event.trigger(map, 'resize');
infoWindow = new google.maps.InfoWindow();
locationSelect = document.getElementById("locationSelect");
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
if (markerNum != "none"){
google.maps.event.trigger(markers[markerNum], 'click');
}
};
}
function searchLocations() {
var address = document.getElementById("addressInput").value;
var subject_text = $('#search_subject>option:selected').text();
var subject_id = $('#search_subject>option:selected').val();
console.log(address);
console.log(subject_text);
console.log(subject_id);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$('#container').replaceWith(addmap);
$("#map").slideDown("4000", function(){
$('#map').after(addLocationSelect);
load();
searchLocationsNear(results[0].geometry.location);
});
} else {
alert(address + ' not found');
}
});
}
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
locationSelect.innerHTML = "";
var option = document.createElement("option");
option.value = "none";
option.innerHTML = "See all results:";
locationSelect.appendChild(option);
}
function searchLocationsNear(center) {
clearLocations();
var searchUrl = 'findlocations.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=20';
downloadUrl(searchUrl, function(data) {
var xml = parseXml(data);
var markerNodes = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerNodes.length; i++) {
var name = markerNodes[i].getAttribute("name");
var address = markerNodes[i].getAttribute("address");
var distance = parseFloat(markerNodes[i].getAttribute("distance"));
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
createOption(name, distance, i);
createMarker(latlng, name, address);
bounds.extend(latlng);
}
map.fitBounds(bounds);
locationSelect.style.visibility = "visible";
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
google.maps.event.trigger(markers[markerNum], 'click');
};
});
}
function createMarker(latlng, name, address) {
var html = "<h3>" + name + "</h3><p>The biography will go here</p>";
var marker = new google.maps.Marker({
map: map,
position: latlng
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
markers.push(marker);
}
function createOption(name, distance, num) {
var option = document.createElement("option");
option.value = num;
option.innerHTML = name + " is " + distance.toFixed(1) + "miles away";
locationSelect.appendChild(option);
}
createOption() does exactly as it says it creates a new option. If you want to add the results of a new search (including markers) you will need to add these to the existing locations.
pseudo code NOT tested
GLOBAL var flag = 0;\\Set to 0 for 1st Search
IN searchLocationsNear() add following
searchLocationsNear(center) {
if(flag ==0){//1st Search
clearLocations();
}else{//Sugsequent Searches
flag =1;
}
The problem is that the locationSelect select dropdown is added every time searchLocations function returns. I just moved it to the top of the function and it's added fresh every time the submit button is entered, which will only provide a single dropdown with the results for the map.
function searchLocations() {
$('#container').replaceWith(addmap);
var address = document.getElementById("addressInput").value;
alert(address);
var subject_text = $('#search_subject>option:selected').text();
var subject_id = $('#search_subject>option:selected').val();
console.log(address);
console.log(subject_text);
console.log(subject_id);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$("#map").slideDown("4000", function(){
load();
searchLocationsNear(results[0].geometry.location);
});
} else {
alert(address + ' not found');
}
});
}
Im trying to change geocoded informations from Schwartmecke 49, 57399 Kirchhundem, Germany to just Schwartmecke 49, Germany , but dont know how. Can anybode help me ? Thanks
<script type="text/javascript">
var map;
var geocoder;
var centerChangedLast;
var reverseGeocodedLast;
var currentReverseGeocodeResponse;
function initialize() {
var latlng = new google.maps.LatLng(49.624935522974546, 15.46877500000007);
var myOptions = {
zoom: 7,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder = new google.maps.Geocoder();
setupEvents();
centerChanged();
}
function setupEvents() {
reverseGeocodedLast = new Date();
centerChangedLast = new Date();
setInterval(function() {
if((new Date()).getSeconds() - centerChangedLast.getSeconds() > 1) {
if(reverseGeocodedLast.getTime() < centerChangedLast.getTime())
reverseGeocode();
}
}, 1000);
google.maps.event.addListener(map, 'zoom_changed', function() {
document.getElementById("zoom_level").innerHTML = map.getZoom();
});
google.maps.event.addListener(map, 'center_changed', centerChanged);
google.maps.event.addDomListener(document.getElementById('crosshair'),'dblclick', function() {
map.setZoom(map.getZoom() + 1);
});
}
function getCenterLatText() {
return '(' + map.getCenter().lat() +')';
}
function getCenterLngText() {
return '(' + map.getCenter().lng() +')';
}
function centerChanged() {
centerChangedLast = new Date();
var lat = getCenterLatText();
var lng = getCenterLngText();
document.getElementById('lat').innerHTML = lat;
document.getElementById('lng').innerHTML = lng;
document.getElementById('formatedAddress').value = '';
currentReverseGeocodeResponse = null;
}
function reverseGeocode() {
reverseGeocodedLast = new Date();
geocoder.geocode({latLng:map.getCenter()},reverseGeocodeResult);
}
function reverseGeocodeResult(results, status) {
currentReverseGeocodeResponse = results;
if(status == 'OK') {
if(results.length == 0) {
document.getElementById('formatedAddress').value = 'None';
} else {
document.getElementById('formatedAddress').value = results[0].formatted_address;
}
} else {
document.getElementById('formatedAddress').value = 'Error';
}
}
function geocode() {
var address = document.getElementById("address").value;
geocoder.geocode({
'address': address,
'partialmatch': true}, geocodeResult);
}
function geocodeResult(results, status) {
if (status == 'OK' && results.length > 0) {
map.fitBounds(results[0].geometry.viewport);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
}
function addMarkerAtCenter() {
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map
});
if(currentReverseGeocodeResponse) {
var addr = '';
if(currentReverseGeocodeResponse.size == 0) {
addr = 'None';
} else {
addr = currentReverseGeocodeResponse[0].formatted_address;
}
text = '<br>' + 'address: <br>' + addr;
}
var infowindow = new google.maps.InfoWindow({ content: text });
}
</script>
Hope i explained my problem enough.
In your reverseGeocodeResult() function, you take the first result and return its "formatted address" property.
Instead of returning this, try browsing its "address_components" property.
See more at
https://developers.google.com/maps/documentation/geocoding/#JSON