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
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>
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
Google map is not showing the exact location. I'm taking the address from our clients and will display them the map. I cross checked the google lat and long with mine, it is not returning the exact values. Here is my code, if I am wrong, please guide me.
function callMap() {
var fullAddress = address + "," + city + "," + state + "," + zip;
var lat_Company = "";
var lng_Company = "";
geocoder.geocode({
'address': fullAddress
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat_Company = parseFloat(results[0].geometry.location.lat());
lng_Company = parseFloat(results[0].geometry.location.lng());
var lCompanyObject = new Object();
lCompanyObject.Name = companyDetails.CompanyName;
lCompanyObject.Description = address + "<br/>" + city + ", " + state + "," + zip;
lCompanyObject.FullAddress = address + ", " + city + ", " + state + "," + zip;
lCompanyObject.Lat = lat_Company;
lCompanyObject.Lng = lng_Company;
displayCompany(city, state, "comp_map", "mapinfowindow", lCompanyObject, "fromSideBar");
}
});
var abpoutsideBarBuilder = '<ul>' +
'<li><div id="map_wrapper1">' +
'<div id="comp_map1"></div>' +
'<div id="mapinfowindow"style="display:none" ><b>#name</b><br>#description</div></div></li></ul>';
$('.about_map_addr_businesshours').html(abpoutsideBarBuilder);
}
function displayCompany(pCity, pState, pMapDiv, mapinfowindow, lCompany, from) {
var requestLocation = lCompany.FullAddress;
geocoder.geocode({
'address': requestLocation
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = parseFloat(results[0].geometry.location.lat());
var lng = parseFloat(results[0].geometry.location.lng());
if (lat != null && lng != null) {
centerLat = lat;
centerLng = lng;
initDisplayMap(centerLat, centerLng, pMapDiv, mapinfowindow, lCompany, from);
}
} else {
console.error("Geocode was not successful for the following reason ::" + status);
}
});
}
function initDisplayMap(pCenterLat, pCenterLng, pMapDiv, mapinfowindow, pCompany, from) {
if ($("#" + mapinfowindow).length > 0) {
var latlng = new google.maps.LatLng(pCenterLat, pCenterLng);
var myOptions = {
zoom: 14,
center: latlng,
disableDefaultUI: true,
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById(pMapDiv), myOptions);
var infowindow = null;
infowindow = new google.maps.InfoWindow({});
var LatLngList = new Array();
var marker = pCompany;
var markerHTML = $('#mapinfowindow').clone().html();
if (from.indexOf("fromSideBar") != -1) {
markerHTML = markerHTML.replace("#name", marker.Name);
markerHTML = markerHTML.replace("#description", marker.Description);
} else if (from.indexOf("fromAboutBar") != -1) {
markerHTML = markerHTML.replace("#name", marker.Name);
markerHTML = markerHTML.replace("#description", marker.Description);
}
if (marker.Lat != null && marker.Lng != null) {
var myLatLng = new google.maps.LatLng(marker.Lat, marker.Lng);
LatLngList[LatLngList.length] = myLatLng;
var beachMarker = new google.maps.Marker({
position: myLatLng,
map: map,
clickable: true,
html: markerHTML
});
google.maps.event.addListener(beachMarker, 'click', function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
var bounds = new google.maps.LatLngBounds();
if (LatLngList.length > 1) {
for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) {
// And increase the bounds to take this point
bounds.extend(LatLngList[i]);
}
//Fit these bounds to the map
map.fitBounds(bounds);
map.setZoom(map.getBoundsZoomLevel(bounds));
map.setCenter(beachMarker.getPosition());
}
}
}
}
Don't mix up geocoder an places.
Nakedcherry Waxing Boutique 6th Street Parkhurst,South Africa
the bold part of this string obviously isn't a address-component.
Expecting the desired result is as when I would expect to get my location for a query like
Dr.Molle,Berlin,Germany
The result you get by the geocoder is for 6th Street Parkhurst,South Africa, and the result is correct.
When you look for a place use the places-textsearch, the result for the given query will be: -26.1437060,28.0207660
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.
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);
}