I can't seem to get the markers to show up for Internet Explorer, despite it working fine on other browsers.
When I run it on IE, it makes me debug it and gives the error.
"Line: 173
Error: 'console' is undefined"
<script type='text/javascript'>
var markerList = new Array();
var propertyList = new Array();
var itemDisplayList = new Array();
var geocoder;
var map;
var latLng;
var browserSupportFlag = new Boolean();
var yaml;
var currentWindow = null;
var addr = "Kansas, KA"
function initialize() {
newMap();
showAllProperties();
<% #yaml = YAML.load(File.read("config/property.yml")) %>
<%
addr = []
name = []
link = []
contact = []
#yaml.each do |property|
prop = Property.new(property)
addr << prop.format_address
contact << prop.format_contact_info
name << prop.property
link << prop.link
end
%>
var addresses = <%= addr.to_json %>;
var names = <%= name.to_json %>;
var contacts = <%= contact.to_json %>;
var links = <%= link.to_json %>;
var i = 0;
function slow_addMarker(){
if(i < addresses.length){
var propertyObj = {address: addresses[i], name: names[i], link: links[i], contact: contacts[i]};
propertyList.push(propertyObj);
addMarker(propertyObj, i);
i++;
if (i < addresses.length){
timeout = setTimeout(slow_addMarker,500);
}
}
}
slow_addMarker();
/*
for(var i = 0; i < addresses.length; i++)
{
var propertyObj = {address: addresses[i], name: names[i], link: links[i], contact: contacts[i]};
propertyList.push(propertyObj);
addMarker(propertyObj, i); //We need to specify the id or else items can be populated in the wrong order due to difference in API call timing
}
*/
itemDisplayList = $('.locations li');
}
function newMap()
{
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: 4,
mapTypeId: google.maps.MapTypeId.HYBRID
}; //end of my options
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder.geocode({'address': addr}, function(results, status)
{
if(status == google.maps.GeocoderStatus.OK)
{
latLng = results[0].geometry.location;
map.setCenter(latLng);
// var marker = new google.maps.Marker(
// {
// // map: map,
// position: latLng
// // icon: "/images/common/gmap_blue_icon.png",
// // shadow: "/images/common/shadow50.png"
// });
// google.maps.event.addListener(marker, 'click', function()
// {
// if (currentWindow != null)
// {
// currentWindow.close();
// }
// infoWindowHere.open(map,marker);
// currentWindow = infoWindowHere;
// });
}
else
{
alert("Geocode was not successful for the following reason: " + status);
latLng = new google.maps.LatLng(0.0, 0.0);
}
});
}
function handleNoGeolocation(errorFlag)
{
if(errorFlag == true)
{
alert("Geolocation service failed.");
geocoder.geocode( { 'address': "<%= Property.new(YAML.load(File.read("config/property.yml"))[0]).format_address%>"}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.location);
}
else
{
alert("Geocode was not successful for the following reason: " + status);
}
});
}
else
{
alert("Your browser doesn't support geolocation.");
geocoder.geocode( { 'address': "<%= Property.new(YAML.load(File.read("config/property.yml"))[0]).format_address%>"}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.location);
}
else
{
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
function addInfoWindow(propertyObject)
{
var contentStr =''+
'<div id="siteNotice">'+
'<h2>'+ propertyObject.name +'</h2>'+
'<p>'+ propertyObject.address +'</p>'+
'<p>'+ propertyObject.contact +'</p>'+
'<a class="goto" href="'+ propertyObject.link + '">View Details</a>'+
'</div>';
var infoWindow = new google.maps.InfoWindow(
{
map: map,
content: contentStr
});
return infoWindow
}
function addMarker(propertyObject, id)
{
var wait_time = 200 * id;
setTimeout(function(){
geocoder.geocode({'address': propertyObject.address}, function(results, status)
{
if(status == google.maps.GeocoderStatus.OK)
{
var marker = new google.maps.Marker(
{
map: map,
position: results[0].geometry.location
});
markerList[id] = marker;
// google.maps.event.addListener(marker, 'click', function()
// {
// if (currentWindow != null)
// {
// currentWindow.close();
// }
// var infoWindow = addInfoWindow(propertyObject);
// infoWindow.open(map,marker);
// currentWindow = infoWindow;
//
// });
}
else
{
//alert("Geocode was not successful for the following reason: " + status);
if (status = google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(function(){addMarker(propertyObject, id)}, 600); //try to reload it a bit later
}
}
});
}, wait_time);
}
function hideAllMarkers()
{
for( var i = 0; i < markerList.length; i++)
{
markerList[i].setVisible(false);
}
}
function openWindow(map, marker)
{
// // if currentWindow != null
// // google.maps.event.trigger(currentWindow, 'closeclick');
// var infoWindow = addInfoWindow(propertyObject);
// infoWindow.open(map,marker);
// currentWindow = infoWindow;
}
function showAllProperties()
{
for(var i = 0; i < propertyList.length; i++)
{
markerList[i].setVisible(true);
$(itemDisplayList[i]).show('slow');
}
}
function showOneCity(city)
{
for(var i = 0; i < propertyList.length; i++)
{
if(propertyList[i].address.search(city) != -1)
{
markerList[i].setVisible(true);
$(itemDisplayList[i]).show('slow');
}
else
{
markerList[i].setVisible(false);
$(itemDisplayList[i]).hide('slow');
}
}
}
function showOneProperty(property)
{
for(var i = 0; i < propertyList.length; i++)
{
// alert(propertyList[i].name + " " + property)
if(propertyList[i].name == property)
markerList[i].setVisible(true);
else
markerList[i].setVisible(false);
}
}
</script>
There is no console in IE. Remove or comment out line 173 (or write a console replacement function). Once you do that it seems to work fine.
Related
I have following javascript code:
function getLatLng() {
var geocoder = new google.maps.Geocoder();
var address = document.getElementById('address2').value;
var input = document.getElementById('address2');
var options = {
types: [],
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latLng = results[0].geometry.location;
$('#lat').val(results[0].geometry.location.lat());
$('#lng').val(results[0].geometry.location.lng());
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function getLatLng2() {
var geocoder = new google.maps.Geocoder();
var e = document.getElementById('city');
var address = e.options[e.selectedIndex].text;
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latLng = results[0].geometry.location;
$('#lat').val(results[0].geometry.location.lat());
$('#lng').val(results[0].geometry.location.lng());
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function getLatLng3() {
var geocoder = new google.maps.Geocoder();
var e = document.getElementById('region');
var address = e.options[e.selectedIndex].text;
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latLng = results[0].geometry.location;
$('#lat').val(results[0].geometry.location.lat());
$('#lng').val(results[0].geometry.location.lng());
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function getLatLng4() {
var geocoder = new google.maps.Geocoder();
var e = document.getElementById('province');
var address = e.options[e.selectedIndex].text;
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latLng = results[0].geometry.location;
$('#lat').val(results[0].geometry.location.lat());
$('#lng').val(results[0].geometry.location.lng());
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function getLatLng5() {
var geocoder = new google.maps.Geocoder();
var e = document.getElementById('country');
var address = e.options[e.selectedIndex].text;
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latLng = results[0].geometry.location;
$('#lat').val(results[0].geometry.location.lat());
$('#lng').val(results[0].geometry.location.lng());
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function getLatLng6() {
var geocoder = new google.maps.Geocoder();
var e = document.getElementById('continent');
var address = e.options[e.selectedIndex].text;
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latLng = results[0].geometry.location;
$('#lat').val(results[0].geometry.location.lat());
$('#lng').val(results[0].geometry.location.lng());
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
//
var whos = null;
var placedata = [];
var geocoder = new google.maps.Geocoder();
var map;
function getplaces(gid, src) {
if ( !! placedata[gid]) {
map.setCenter({
lat: parseFloat(placedata[gid].lat),
lng: parseFloat(placedata[gid].lng)
});
switch (src) {
case "continent":
map.setZoom(3);
break;
case "country":
map.setZoom(5);
break;
case "province":
map.setZoom(6);
break;
case "region":
map.setZoom(7);
break;
case "city":
map.setZoom(8);
break;
}
codeAddress(placedata[gid].name);
}
whos = src;
// var request = "http://ws.geonames.org/childrenJSON?geonameId="+gid+"&callback=getLocation&style=long";
var request = "http://www.geonames.org/childrenJSON?geonameId=" + gid + "&callback=listPlaces&style=long";
aObj = new JSONscriptRequest(request);
aObj.buildScriptTag();
aObj.addScriptTag();
}
function listPlaces(jData) {
counts = jData.geonames.length < jData.totalResultsCount ? jData.geonames.length : jData.totalResultsCount;
who = document.getElementById(whos);
who.options.length = 0;
if (counts) who.options[who.options.length] = new Option('Select', '');
else who.options[who.options.length] = new Option('No Data Available', 'NULL');
for (var i = 0; i < counts; i++) {
who.options[who.options.length] = new Option(jData.geonames[i].name, jData.geonames[i].geonameId);
placedata[jData.geonames[i].geonameId] = jData.geonames[i];
}
delete jData;
jData = null;
}
function zoomto(gid) {
if ( !! placedata[gid]) {
map.setCenter({
lat: parseFloat(placedata[gid].lat),
lng: parseFloat(placedata[gid].lng)
});
map.setZoom(14);
}
}
function codeAddress(address) {
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (!!results && !!results[0] && !!results[0].geometry && !!results[0].geometry.viewport) {
map.fitBounds(results[0].geometry.viewport);
} else if (!!results && !!results[0] && !!results[0].geometry && !!results.geometry.bounds) {
map.fitBounds(results[0].geometry.bounds);
} else {
map.setCenter(results[0].geometry.location);
}
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function codeAddress2() {
var address = document.getElementById('address2').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
window.onload = function () {
getplaces(6295630, 'continent');
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 3,
center: {
lat: 0,
lng: 0
}
});
};
complete demo is here (fiddle)
Selecting Continent, state, region, etc I get latitude and longitude
If I insert a draggable marker:
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
draggable:true,
title: 'Drag Me!'
});
Moving the marker in the map I want change in real time continent, state, city, etc in the menu. Is it possible? How?
You can search the drop down "options" for the returned result from the geocoder. It is possible that as the data comes from different sources, it may not find the correct result, but this works for me (at least for Wichita, KS), although it requires a drag for each address component. At this point, to change that you would need to refactor your code.
function setDropdown(menuId, string) {
var menu = document.getElementById(menuId);
var selectedIndex = menu.selectedIndex;
for (var option = 0; option < menu.options.length; option++) {
if (nodeValue(menu.options[option]).indexOf(string) != -1) {
if (selectedIndex != option) {
menu.options[option].setAttribute("selected", "selected");
menu.onchange();
}
break;
}
}
}
function displayAddress(address) {
for (var p = address.length - 1; p >= 0; p--) {
for (var t = 0; t < address[p].types.length; t++) {
if (address[p].types[t] == "country") {
setDropdown('country', address[p].long_name);
}
if (address[p].types[t] == "administrative_area_level_1") {
console.log("admin_area_level_1=" + address[p].long_name);
setDropdown('province', address[p].long_name)
}
if (address[p].types[t] == "administrative_area_level_2") {
console.log("admin_area_level_2=" + address[p].long_name);
setDropdown('region', address[p].long_name)
}
if (address[p].types[t] == "locality") {
console.log("locality=" + address[p].long_name);
setDropdown('city', address[p].long_name);
}
}
}
}
proof of concept fiddle
I would like to display a map that limits nearby results to a category that I designate. I have code that allows for the user to complete their own search, but would like to modify so that the search is disabled and the category is predefined. Source: http://www.gurchet-rai.net/apps/places/
$(document).ready(function(){
var loc;
var map;
var service;
var infoWindow;
var overlays = [];
var resultList = [];
var isMobile = $(window).width < 767;
try {
if (typeof navigator.geolocation !== 'undefined') {
navigator.geolocation.getCurrentPosition (
function(position) {
var coords = position.coords;
loc = new google.maps.LatLng(coords.latitude, coords.longitude);
map = new google.maps.Map(document.getElementById("map_canvas"), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
center: loc,
zoom: 13
});
service = new google.maps.places.PlacesService(map);
infoWindow = new google.maps.InfoWindow();
},
function(error) {
if (error.code == 1) {
$('#location-details').append('Please enable location tracking in your web browser');
} else if (error.code == 2) {
$('#location-details').append('Unable to determine location - please ensure location tracking is enabled in your browser');
} else {
$('#location-details').append('Unable to determine location');
}
},
{enableHighAccuracy: true}
);
} else {
$('#location-details').append('Your browser does not support location tracking');
}
} catch (e) {
alert('An error has occured');
}
function plotResultList(){
var iterator = 0;
for(var i = 0; i < resultList.length; i++){
setTimeout(function(){
var lat = resultList[iterator].geometry.location.Za;
var lng = resultList[iterator].geometry.location.Ya;
var name = resultList[iterator].name;
var addr = resultList[iterator].formatted_address;
var reference = resultList[iterator].reference;
var marker = new google.maps.Marker({
position: resultList[iterator].geometry.location,
map: map,
title: name,
animation: isMobile? 'undefined' : google.maps.Animation.DROP
});
overlays.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infoWindow.close();
var request = {
reference: reference
};
service.getDetails(request, function(place, status){
var content = "<h6>" + name + "</h6>";
if(status == google.maps.places.PlacesServiceStatus.OK){
if(typeof place.rating !== 'undefined'){
var badgeType = '';
if (place.rating < 2){
badgeType = 'badge-important';
} else if (place.rating >= 2 && place.rating <= 3){
badgeType = 'badge-warning';
} else {
badgeType = 'badge-success';
}
content += "<p><small>Rating: <span class='badge " + badgeType + "'>" + place.rating + "</span></small></p>";
}
if(typeof place.formatted_address !== 'undefined'){
content += "<br><small>" + place.formatted_address + "</small>";
}
if(typeof place.formatted_phone_number !== 'undefined'){
content += "<br><small><a href='tel:" + place.formatted_phone_number + "'>" + place.formatted_phone_number + "</a></small>";
}
if(typeof place.website !== 'undefined'){
content += "<br><small><a href='" + place.website + "'>website</a></small>";
}
}
infoWindow.setContent(content);
infoWindow.open(map, marker);
});
});
iterator++;
}, isMobile? 0: (i * 75));
}
}
$('#search').submit(function(e){
e.preventDefault();
var query = $('#query').val();
var request = {
location: map.getCenter(),
radius: '5000',
query: query
};
service.textSearch(request, function(results, status, pagination){
for(var i = 0; i < overlays.length; i++){
overlays[i].setMap(null);
}
resultList.length = 0;
overlays.length = 0;
if (status == google.maps.places.PlacesServiceStatus.OK) {
resultList = resultList.concat(results);
plotResultList();
}
});
});
});
Take a look on Maps Javascript API, specifically in the types parameter. Here are described the allowed types.
Let's say you want to show airports based on user's search, your request will be:
var request = {
location: map.getCenter(),
radius: '5000',
query: query,
types: ['airport']
};
I am working on a map based search project,Visit http://indiahomeplus.com/mapview.php ,
here the center of the map is not stable , i have given its center to kolkata but it changes automatically to unknown place.
And there is also a s
Can anyone pl's check this issue.
here is the js.
//<![CDATA[
var map;
var markers = [];
var infoWindow;
var locationSelect;
var iCircle;
function init() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(22.607672, 88.399901),
zoom: 12,
mapTypeId: 'roadmap',
minZoom: 8,
mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU }
});
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');
}
}; searchLocationsNear(new google.maps.LatLng(22.607672, 88.399901));
//alert("in init");
var distanceWidget = new DistanceWidget(map);
// getmarkers();
}
function searchLocations() {
var address = document.getElementById("addressInput").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ address: address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
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 radius = document.getElementById('radiusSelect').value;
var searchUrl = 'phpsqlsearch_genxml.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
downloadUrl(searchUrl, function (data) {
var xml = parseXml(data);
var markerNodes = xml.documentElement.getElementsByTagName("property");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerNodes.length; i++) {
var name = markerNodes[i].getAttribute("name");
var pid = markerNodes[i].getAttribute("pid");
//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")));
//alert(pid);
createOption(name, distance, i);
createMarker(latlng, name,pid);
bounds.extend(latlng);
// sidebar(pid, 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,pid) {
var html = "<b>" + name +","+pid+ "</b>";
var marker = new google.maps.Marker({
map: map,
position: latlng,
visible:false //, icon:'images/marker_p1.png'
});
google.maps.event.addListener(marker, 'click', function () {
show_right_div(pid);
//showxx();
});
google.maps.event.addListener(marker, 'mouseover', function () {
infoWindow.setContent(html);
infoWindow.open(map, marker);
// alert(marker);
});
google.maps.event.addListener(marker, 'mouseout', function () {
infoWindow.close();
});
markers.push(marker);
}
function createOption(name, distance, num) {
var option = document.createElement("option");
option.value = num;
option.innerHTML = name + "(" + distance.toFixed(1) + ")";
locationSelect.appendChild(option);
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function () {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
function doNothing() { }
google.maps.event.addDomListener(window, 'load', init);
//]]>
function hide_right_div() {
right_div.style.visibility = "hidden";
}
function show_right_div(str) {
right_div.style.visibility = "visible";
boxclose.style.visibility="visible"
if (str == "")
{
document.getElementById("right_div").innerHTML = "";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("right_div").innerHTML = xmlhttp.responseText;
resp = xmlhttp.responseText;
parseScript(resp);
}
}
xmlhttp.open("GET", "getproperty_view.php?q=" + str, true);
xmlhttp.send();
//parseScript(resp);
}
function parseScript(strcode) {
var scripts = new Array(); // Array which will store the script's code
// Strip out tags
while(strcode.indexOf("<script") > -1 || strcode.indexOf("</script") > -1) {
var s = strcode.indexOf("<script");
var s_e = strcode.indexOf(">", s);
var e = strcode.indexOf("</script", s);
var e_e = strcode.indexOf(">", e);
// Add to scripts array
scripts.push(strcode.substring(s_e+1, e));
// Strip from strcode
strcode = strcode.substring(0, s) + strcode.substring(e_e+1);
}
// Loop through every script collected and eval it
for(var i=0; i<scripts.length; i++) {
try {
eval(scripts[i]);
}
catch(ex) {
// do what you want here when a script fails
}
}
}
The workflow of your script is:
call init where you create the map and call...
searchLocationsNear...where you send a request to
http://indiahomeplus.com/phpsqlsearch_genxml.php?lat=22.607672&lng=88.399901&radius=25
this response of this script is Not connected : in the....
callback for the above request you create a LatLngBounds-object and extend it with locations based on the response(which will not happen, because the response doesn't contain markers) . Later you call ...
map.fitBounds(bounds); the inital bounds of a google.maps.LatLngBounds seems to be
((1,180),(-1,-180))
...the viewport of the map will be set to fit these bounds, that's the result you see.
Possible solution: immediately leave the callback when there are no markers :
if(!markerNodes.length)return;
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