I have the following code which should display several markers for places in an array and each marker on click will display an info window everything works fine except that out of 21 places I am able to display only 8 Markers.
// declare Variables
var geocoder;
var map;
var tex;
var markersArray = [];
// pids array 21 addreses
var pids = [{ad:'251 Pantigo Road Hampton Bays NY 11946',pid:'9'},
{ad:'Amagensett Quiogue NY 11978',pid:'10'},
{ad:'789 Main Street Hampton Bays NY 11946',pid:'12'},
{ad:'30 Abrahams Path Hampton Bays NY 11946',pid:'14'},
{ad:'3 Winnebogue Ln Westhampton NY 11977',pid:'15'},
{ad:'44 White Oak Lane Montauk NY 11954',pid:'16'},
{ad:'107 stoney hill road Bridgehampton NY 11932',pid:'17'},
{ad:'250 Pantigo Rd Hampton Bays NY 11946',pid:'19'},
{ad:'250 Pantigo Rd Hampton Bays NY 11946',pid:'20'},
{ad:'44 Woodruff Lane Wainscott NY 11975',pid:'21'},
{ad:'Address East Hampton NY 11937',pid:'46'},
{ad:'Address Amagansett NY 11930',pid:'49'},
{ad:'Address Remsenburg NY 11960 ',pid:'50'},
{ad:'Address Westhampton NY 11977',pid:'51'},
{ad:'prop address Westhampton Dunes NY 11978',pid:'52'},
{ad:'prop address East Hampton NY 11937',pid:'53'},
{ad:'Address East Hampton NY 11937',pid:'58'},
{ad:'Address Southampton NY 11968',pid:'59'},
{ad:'Address Bridgehampton NY 11932',pid:'60'},
{ad:'Address Sagaponack NY 11962',pid:'61'}];
// create an MVCobject for creating Info window on marker
var pin = new google.maps.MVCObject();
// The content placeholder for the Info window.
var content = document.createElement("DIV");
var title = document.createElement("DIV");
content.appendChild(title);
// that is where you have the ajax result placed
var streetview = document.createElement("DIV");
streetview.style.width = "326px";
streetview.style.height = "212px";
content.appendChild(streetview);
var infowindow = new google.maps.InfoWindow({
content: content
});
// Initialize
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.8687097, -73.0014946);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
getAllPids();
}
// loop to create all markers
function getAllPids() {
var i;
for (i = 0; i < pids.length; i++) {
var test = pids[i];
codeAddress(test);
}
}
// get latlng for each address , create marker and add eventlistner to click open infowindow
function codeAddress(place) {
geocoder.geocode({ 'address': place.ad }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: place.pid
});
markersArray.push(marker);
google.maps.event.addListener(marker, "click", function() {
openInfoWindow(marker);
});
} else {
// alert("Geocode was not successful for the following reason: " + status);
}
});
}
// click event on marker calls this to show infowindow.
function openInfoWindow(marker) {
getContent(marker.getTitle());
pin.set("position", marker.getPosition());
infowindow.open(map, marker);
}
// Now ajax call to get the content for the current info window
function getContent(pid) {
$.ajax({
type: "POST",
url: "mapSearchResult.aspx/get_map",
data: "{'pids':'"+pid +"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
title.innerHTML =msg.d;
}
});
}
If you uncommented this
// alert("Geocode was not successful for the following reason: " + status);
you would find that the reason code is OVER_QUERY_LIMIT (620).
There is a rate limit: if you geocode many addresses without introducing a delay between them you will break that limit because you are doing too many in too short a time.
Some of your addresses won't geocode (or won't produce the result you want), because the geocoder uses postal addresses. Addresses like Address East Hampton NY 11937 or prop address Westhampton Dunes NY 11978 aren't postal addresses.
The recommended strategy is not to waste Google's resources which you share with others. Geocode your addresses yourself in a one-off operation, store those locations in your database (or use them directly in code) and then use the coordinates to position markers. Don't bother to find locations you already know about every time the page is loaded. Only use the geocoder to find locations you don't know in advance: addresses entered by your users.
If you really must subvert that strategy and geocode everything all the time, then you need to slow the requests down. As you submit more requests, you will probably have to slow them down more to satisfy the geocoder. I've made a Version 3 example (from a noted Version 2 example) at http://acleach.me.uk/gmaps/v3/plotaddresses.htm — you can see it starts out with a 100ms delay between requests, but needs to slow down to around 150ms after twenty iterations.
Related
Here I got stucked with one functionality in my demo page. Here I want to take a snapshot of what i can see (google map) which is adjustable by user.
Now I want when I was click one button i take the screenshot which I saw on the screen and open this screen shot in that window below the map and also i want to download that screenshot.
Here I can put my demo code here. In this code where I can insert that code and which code is usuful for it.
Hope for getting very fast reply with positive answer.
Thank You in Advance...
My Code IS:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title></title>
</head><body>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var markers = [
{
"title": 'Abingdon',
"lat": '40.803572',
"lng": '-90.400770',
"description": 'Abingdon is a city in Knox County, Illinois, 50 miles (80 km) west of Peoria. It is part of the Galesburg Micropolitan Statistical Area. The city was first settled in 1828 and was incorporated in 1857. In 1894, the patent for the common spring-loaded mousetrap was awarded to William Hooker of Abingdon. In 1890, 1,321 people lived here; in 1900, 2,022; and in 1910, 2,464. The population was 3,612 at the 2000 census.'
}
,
{
"title": 'Cedar Rapids',
"lat": '41.9831',
"lng": '-91.6686',
"description": 'A flourishing center for arts and culture in Eastern Iowa, the city is home to the Cedar Rapids Museum of Art, the National Czech & Slovak Museum & Library, the Paramount Theatre, Theatre Cedar Rapids, the African-American Historical Museum and Cultural Center of Iowa, and the Iowa Cultural Corridor Alliance. Cedar Rapids is an economic hub of the state, located in the core of the Interstate 380.'
}
,
{
"title": 'Chicago',
"lat": '41.8369',
"lng": '-87.6847',
"description": 'Chicago was incorporated as a city in 1837, near a portage between the Great Lakes and the Mississippi River watershed, and grew rapidly in the mid-nineteenth century.[7] The city is an international hub for finance, commerce, industry, technology, telecommunications, and transportation: OHare International Airport is the busiest airport in the world when measured by aircraft traffic; it also has the largest number of U.S. highways and rail road freight.'
}
,
{
"title": 'Orland Park',
"lat": '41.6073508',
"lng": '-87.8616741',
"description": 'Orland Park is a village in Cook County, Illinois, United States, and a middle-class suburb of Chicago which in 2010 had a population of 56,767.'
}
];
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
var infoWindow = new google.maps.InfoWindow();
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title
});
latlngbounds.extend(marker.position);
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
//***********ROUTING****************//
//Intialize the Path Array
var path = new google.maps.MVCArray();
//Intialize the Direction Service
var service = new google.maps.DirectionsService();
//Set the Path Stroke Color
var poly = new google.maps.Polyline({ map: map, strokeColor: '#252365' });
//Loop and Draw Path Route between the Points on MAP
for (var i = 0; i < lat_lng.length; i++) {
if ((i + 1) < lat_lng.length) {
var src = lat_lng[i];
var des = lat_lng[i + 1];
path.push(src);
poly.setPath(path);
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
}
});
}
}
}
</script>
<div id="dvMap" style="width: 700px; height: 500px">
</div>
I’m having problems upgrading to Google Maps v3 from v2. In particular with MarkerManager. I haven’t worked with maps before and am helping out someone whose developer abandoned them who developed the maps in v2.
The map is to show a maximum of 100 markers that when clicked on show an infobox. (There is also a telerik RadGrid bound to with the results.) It all seems to work until it gets into DisplayAllMarkers() mgr.addMarkers() (see below). It fails in ProjectionHelperOverlay.prototype.LatLngToPixel with Uncaught TypeError: Cannot call method ‘lng’ of undefined. I’ve tried putting in alerts in AddMarker if lat or lng are undefined, but none were alerted. The previous calls to MarkerManager.prototype.addMarkerBatch_ set mPoint to undefined which was then passed to getTilePoint which calls LatLngToPixel where it fails.
I’m thinking it’s a problem with listeners, but have tried various listeners without success. I would really appreciate some help with this as I have been unable to make progress for some time and am letting down the client and don’t know what to try next.
Select SearchResult.js snippet of code:
$(document).ready(function () {
InitializeMap(originalScale);
});
var map;
var batch = [];
var mgr;
var geocoder = null;
function InitializeMap(scale) {
map = new google.maps.Map(
document.getElementById('MapContainer'), {
center: new google.maps.LatLng(Latitude, Longitude),
zoom: scale,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
});
var listener = google.maps.event.addListener(map, "bounds_changed", function () {
MapMoved();
google.maps.event.removeListener(listener);
});
}
var south, west, north, east, zoom;
function MapMoved() {
zoom = map.getZoom();
//zoom = map.setZoom();
var bounds = map.getBounds();
var sw = bounds.getSouthWest();
var ne = bounds.getNorthEast();
south = sw.lat();
west = sw.lng();
north = ne.lat();
east = ne.lng();
Search();
}
The Search(); loads up the search parameters (including the north, south, east, west co-ordinates) and calls a telerik ajax request.
C# snippet:
if (Properties.Count >= 1 || zoom == "0") //display properties
{
RadAjaxManager1.ResponseScripts.Add("ClearAll();");
Properties.ForEach(p =>
{
string script = "AddMarker(" + p.ID.ToString() + "," + p.LatitudeShort.ToString() + "," + p.LongitudeShort.ToString() + ");";
RadAjaxManager1.ResponseScripts.Add(script);
});
RadAjaxManager1.ResponseScripts.Add("DisplayAllMarkers();");
}
else //zoom out map – which will start the search process all over again.
{
string delta = "1";
RadAjaxManager1.ResponseScripts.Add("ZoomOut(" + delta + ");");
}
SearchResult.js snippet continued:
function ClearAll() {
batch = [];
}
function AddMarker(id, lat, lng) {
batch.push(CreatePropertyMarker(lat, lng, id));
}
function DisplayAllMarkers() {
mgr = new MarkerManager(map, { trackMarkers: true });
google.maps.event.addListener(mgr, 'loaded', function () {
mgr.clearMarkers();
mgr.addMarkers(batch, 3, 17); // **Failing in here!!!**
mgr.refresh();
});
}
function CreatePropertyMarker(lat, lng, id) {
var redIcon3 = {
url: '../images/HouseIcon_ForGoogleMap.png',
size: new google.maps.Size(22, 22),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(0, 22)
};
var marker3 = new google.maps.Marker(new google.maps.LatLng(lat, lng), redIcon3);
google.maps.event.addListener(marker3, 'click', function () {
var data = "{'Id': '" + id + "'}";
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: 'searchresult.aspx/GetPropertyPopOut',
data: data,
success: function (data) {
var popout = data.d;
marker3.openExtInfoWindow(map, "custom_info_window_red", popout, { beakOffset: -1 });
},
error: function (result) {
alert('status:' + result.status + ' statusText:' + result.statusText);
}
});
});
return marker3;
}
Script order and versions:
jquery-ui-1.9.1.custom.min.css
Google Maps: v3 (I have also tried specifying particular version 3 numbers e.g. v=3.12 http://maps.googleapis.com/maps/api/js?key=MY_KEY&sensor=false
jquery-1.8.2.js
jquery-ui-1.9.1.custom.min.js
extinfowindow.js v2.0
MarkerManager.js v1.1
SearchResult.js
jquery-ui-1.8.16.custom.min.js
jquery-1.6.2.min.js
After tying a load of different things I eventually found out the problem was when creating the marker it needed position set. I changed the line in CreatePropertyMarker from:
var marker3 = new google.maps.Marker(new google.maps.LatLng(lat, lng), redIcon3);
to:
var marker3 = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
icon: redIcon3
});
In my website I have two panel, left side is for adrress and right side is for google map.
I want to load a google map once I click a particular address without page refresh.
Please help me.
You should implement this via Javascript, the algorithm will be something like this:
Show a map based on a default location (e.g. your city and adequate zoom level to this)
a form with a textbox to search and address
An event on click on a "search button" to geocode and get a lat,lon for that address
Re-set via Javascript the center of the map based on the geocode service response
add a marker on location returned from geocoding service.
hope this helps
PD How are you querying the map with the panels right now ?
Geocode the address here is the link on how to go about it
https://developers.google.com/maps/documentation/javascript/geocoding#GeocodingRequests
then do this
map.setMap(latLng)
where map is your global map object
and latLng is co-ordinates obtained from geocode library
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {zoom: 8,center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').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);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<input id="address" type="textbox" value="New Delhi, India">
<input type="button" value="Geocode" onclick="codeAddress()">
I am initializing the Google map using following code:
function googleMapinitialize(fenceAddIn){
var fenceAdd=new google.maps.LatLng(37.2146,121.5545);
var mapProp = {
center:fenceAdd,
zoom:30,
mapTypeId:google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById("fenceMap"),mapProp);
var geocoder = new google.maps.Geocoder();
var location = fenceAddIn; //"2001 Gateway PI, San Jose, CA";
if(!geocoder) {
geocoder = new google.maps.Geocoder();
}
var geocoderRequest = {
address: location
}
var myCity = null;
var marker = null;
var infowindow = null;
geocoder.geocode(geocoderRequest, function(results, status) {
if (status =="" || status == google.maps.GeocoderStatus.ZERO_RESULTS){
alert("'" + location + "' not found!!!");
map.setCenter(fenceAdd);
} else if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
fenceAdd = new google.maps.LatLng(results[0].geometry.location.hb,results[0].geometry.location.ib);
if (!marker) {
marker = new google.maps.Marker({
map: map,
raiseOnDrag:false,
draggable:true
});
marker.setPosition(results[0].geometry.location);
google.maps.event.addListener(marker,'click',function(){
if (!infowindow) {
infowindow = new google.maps.InfoWindow({
disableAutoPan:true,
maxWidth:100
});
}
var content = '<strong>' + results[0].formatted_address + '</strong>';
infowindow.setContent(content);
infowindow.setPosition(results[0].geometry.location);
infowindow.open(map, marker);
});
}
}
myCity = new google.maps.Circle({
center:fenceAdd,
radius:125,
strokeColor:"#0000ff",
strokeOpacity:0.1,
strokeWeight:0.1,
fillColor:"#0000ff",
fillOpacity:0.20,
map:map
});
google.maps.event.addListener(map, 'click', function(){
infowindow.close();
});
google.maps.event.addListener(map, 'dblclick', function(){
window.open("<%=request.getContextPath() %>/jsp/googleMapPopup.jsp?fenceAddress="+$('#haddr').val(),'ADDRESSMAP','height=400,width=600');
});
});
}
I am sending a address which is geocoded and the position marked by a pin on the map. But in case when the geocoding fails the map is centered around china. So to overcome this I am resetting the map center to the original lat long and drawing the circle on it. When I debugged the code I saw that the coordinates are getting set properly but the map is still showing the china map.
Can some tell me how to reset the map location in this case?
Your fenceAdd coordinates default to China:
206 Provincial Road, Muping, Yantai, Shandong, China (37.21401, 121.5955285)
If you don't want the map to center there, change those coordinates.
I have created a code to add multiple markers and infoWindows using the GeoCoding service. I have copied the method from API v3 Docs. My script pulls address information from a ASP.Net web service and writes them onto a hidden div element.
function codeAddress(address)
{
//Get the location information from address
geocoder.geocode( { 'address': address}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
//Add a google marker onto the given address
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: results[0].geometry.location
});
//Prepare a infoWindow to display complete address
var faddress = "<h4>Office Address:</h4><span>" + address + "</span>";
var infowindow = new google.maps.InfoWindow({content: faddress});
//Opening information window on mouseover event of marker
google.maps.event.addListener(marker, 'mouseover', function(){
infowindow.open(map, marker);
});
//closing the info window when mouse is moved out of marker
google.maps.event.addListener(marker, 'mouseout', function(){
infowindow.close();
});
}
});
}
Next piece of code reads the address from hidden div elements and adds the marker along with InfoWindows. This code works perfectly with Internet Explorer 7.0/8.0.
//Populate the result onto div element
$.each(arr,function(index, item){
$(".result").append("<div class='block'>" + item + "</div>");
});
//Loop through the div element and add marker to map
$(".block").each(function(){
codeAddress($(this).text());
})
But the same code is not working when i open it on Firefox 6.0/IE 9.0.
GeoCoding service returns ZERO_RESULTS for the same call. When I call the method 5 times with same address it is able to add markers.
Any idea if geoCoding service has issues with new browsers ?
Thanks in Advance...
Sudhir
this is the code im using to generate maps, you can take it and adjust it to your needs:
var address = document.getElementsByTagName('address')[0].innerHTML;
var title = document.getElementById('contact').getElementsByTagName('h2')[0].innerHTML;
var geocoder;
var map;
geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address },
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var myOptions = {
zoom: 15,
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: title
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});