marker clusterer doesn't cluster when zoom - api

i'm trying to learn google api and i want to use marker clusterer. i create a database
from here and do whatever google said. my code is
`
<script src="markerclusterer.js" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
restaurant: {
icon: 'images/pin1.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
bar: {
icon: 'images/pin2.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function initialize() {
var markers = null;
var mcmarkers = [];
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 12,
mapTypeId: 'satellite'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = data.responseXML;
markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"))
var point = new google.maps.LatLng(lat, lng);
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
mcmarkers.push(marker);
var mc = new MarkerClusterer(map, mcmarkers);
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
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, request.status);
}
};
request.open('POST', url, true);
request.send(null);
}
function doNothing() {}
//]]>
google.maps.event.addDomListener(window, 'load', initialize);
`
it works well when i open for the first time but when i zoom in or out there was no clusters except max zoom out. i couldn't figure it out. thanks for your help...

var mc = new MarkerClusterer(map, mcmarkers);
This line cannot be placed inside the for loop. but outside after it. I did exactly the same mistake:).

Related

Adding graphic layer to map in arcgis java script api

I am using arcgis js api.I have called all necessary esri class modules and all class name in order. I am using query task to add points to map as a graphic layer.I am getting error for graphic.I am not able to trace the error.
var map;
var toc;
var mapserviceurl = "http://......./arcgisserver/rest/services/CRD/CRD1/MapServer";
require(["dojo/parser",
"dojo/on", "esri/map","esri/dijit/HomeButton",
"esri/dijit/Measurement", "dojo/_base/lang","esri/layers/ArcGISDynamicMapServiceLayer",
"esri/layers/FeatureLayer","esri/graphic","esri/layers/GraphicsLayer",
"esri/dijit/Scalebar","esri/dijit/BasemapGallery","esri/toolbars/navigation",
"esri/dijit/OverviewMap","esri/geometry/Extent","esri/SpatialReference",
"esri/geometry/webMercatorUtils","esri/tasks/query","esri/tasks/QueryTask",
"esri/toolbars/draw","esri/symbols/SimpleLineSymbol","esri/symbols/SimpleFillSymbol",
"esri/symbols/PictureMarkerSymbol","esri/symbols/SimpleMarkerSymbol",
"esri/renderers/SimpleRenderer","esri/geometry/Point","esri/Color",
"agsjs/dijit/TOC","esri/InfoTemplate", "esri/tasks/IdentifyTask",
"esri/tasks/IdentifyParameters", "esri/dijit/Popup", "dojo/dom-construct",
"esri/tasks/locator","dojo/_base/array", "dojo/domReady!"],
function (parser, on, Map, HomeButton, Measurement,lang, ArcGISDynamicMapServiceLayer, FeatureLayer, graphic, GraphicsLayer, Scalebar, BasemapGallery, Navigation, OverviewMap, Extent, SpatialReference,
webMercatorUtils, Query, QueryTask, DrawToolbar, SimpleLineSymbol, SimpleFillSymbol,
PictureMarkerSymbol, SimpleMarkerSymbol, SimpleRenderer,Point,Color,TOC,InfoTemplate,IdentifyTask,IdentifyParameters,
Popup,domConstruct,Locator,arrayUtils) {
parser.parse();
createDialogs();
var identifyTask, identifyParams;
var intialextent = new Extent(7778597.959975056, 1564947.1810059766, 9217107.340624947, 2133123.2518000016, new SpatialReference({ wkid: 102100 }));
map = new Map("divMap", {
basemap: "streets",
center: [75, 14],
zoom: 7,
extent: intialextent,
logo: false,
fitExtent: true,
slider: true
});
var operationalLayer = new ArcGISDynamicMapServiceLayer(mapserviceurl);
var samplelocations = new GraphicsLayer({ id: "Samplelocations" });
var samplelocationsSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_CIRCLE, 10, SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([239, 107, 0]), 1), new Color([239, 107, 0]));
var samplelocationrenderer = new SimpleRenderer(samplelocations);
samplelocations.setRenderer(samplelocationrenderer);
var home = new HomeButton({
map: map
}, "HomeButton");
home.startup();
map.on('layers-add-result', function (evt) {
try {
var toc = new TOC({
map: map,
layerInfos: [{
layer: pointFeatureLayer,
title: "My Feature"
}, {
layer: operationalLayer,
title: "Dynamic Map"
}]
}, "tocDiv");
toc.startup();
toc.on("load", function () {
console.log("TOC loaded");
});
}
catch (e) {
console.error(e.message);
}
});
map.addLayers([operationalLayer, pointFeatureLayer, samplelocations]);
var basemapGallery = new BasemapGallery({
showArcGISBasemaps: true,
map: map
}, "basemapGallery");
basemapGallery.on("load", function () {
basemapGallery.remove('basemap_1');
basemapGallery.remove('basemap_2');
basemapGallery.remove('basemap_3');
basemapGallery.remove('basemap_4');
basemapGallery.remove('basemap_5');
basemapGallery.remove('basemap_8');
});
basemapGallery.startup();
var Scalebar = new Scalebar({
map: map,
scalebarUnit: 'metric',
scalebarStyle: 'line'
});
var measurement = new Measurement({
map: map
}, measurementDiv);
measurement.startup();
map.on("mouse-move", showcoordiantes);
map.on("mouse-drag", showcoordiantes);
//overview tools
var OverviewMap = new OverviewMap({
map: map,
attachTo: "bottom-right",
color: " #D84E13",
opacity: .40
});
OverviewMap.startup();
function showcoordiantes(evt) {
var p = webMercatorUtils.webMercatorToGeographic(evt.mapPoint);
$("#latlong").html("Lat,Long : " + p.y.toFixed(4) + "," + p.x.toFixed(4));
}
$("#ClearGraphics").click(function (e) {
e.preventDefault();
// drawtools.deactivate();
map.infoWindow.hide();
map.setMapCursor("default");
map.graphics.clear();
});
var navToolbar = new Navigation(map);
//zoom In
$("#ZoomInTool").click(function (e) {
e.preventDefault();
map.setMapCursor("url('images/cursors/zoomin.cur'), auto");
navToolbar.activate(Navigation.ZOOM_IN);
});
//ZoomOut
$("#ZoomOutTool").click(function (e) {
e.preventDefault();
map.setMapCursor("url('images/cursors/zoomout.cur'), auto");
navToolbar.activate(Navigation.ZOOM_OUT);
});
//Pan
$("#panTool").click(function (e) {
e.preventDefault();
map.setMapCursor("url('images/cursors/pan.cur'), auto");
navToolbar.activate(Navigation.PAN);
});
//FullExtent
$("#zoomfullext").click(function (e) {
e.preventDefault();
map.setMapCursor("default");
navToolbar.deactivate();
// navToolbar.zoomToFullExtent();
map.setExtent(intialextent, true);
});
//Zoom to previous
$("#zoomtoPrevExtent").click(function (e) {
e.preventDefault();
map.setMapCursor("default");
navToolbar.deactivate();
navToolbar.zoomToPrevExtent();
});
//Zoom to Next
$("#zoomtoNextExtent").click(function (e) {
e.preventDefault();
map.setMapCursor("default");
navToolbar.deactivate();
navToolbar.zoomToNextExtent();
});
map.on("load", showresults)
function showresults() {
var queryTask = new esri.tasks.QueryTask('http://......./arcgisserver/rest/services/CRD/CRD2/MapServer/0');
var query = new esri.tasks.Query();
symbol = new esri.symbol.SimpleMarkerSymbol();
symbol.setStyle(esri.symbol.SimpleMarkerSymbol.STYLE_SQUARE);
symbol.setSize(10);
symbol.setColor(new dojo.Color([255, 255, 0, 0.5]));
query.returnGeometry = true;
query.outFields = ["*"];
query.outSpatialReference = map.spatialReference;
query.where = "objectid = '" + 5281902 + "'";
map.graphics.clear();
queryTask.execute(query, addPointsToMap);
function addPointsToMap(featureSet) {
var graphic = featureSet.features;
graphic.setSymbol(symbol);
map.graphics.add(graphic);
var extent = esri.graphicsExtent(features);
if (extent) {
map.setExtent(extent)
}
}
}
});
I am getting error as
You are assigning an array to the graphic variable:
var graphic = featureSet.features;
Select a single feature of the array and set the symbol then e.g.
var graphic = featureSet.features[0];

Google Places API - Getting Phone Number and Website

I believe I need to make follow up calls to get the results I am looking for. However, I cannot get the phone number and www url for any of the results I pull up.
I am a novice and need some help explaining where in this code I can get the correct results pulled. Please see the demo site here:
http://news.yeselectric.com/gmaps-excel-master/
Here is my JS code:
var store = (function () {
var searchBox,
infowindow,
markers = [],
myLatlng = new google.maps.LatLng(50.0019, 10.1419),
myOptions = { zoom: 6, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: false, streetViewControl:false },
customIcons = { iconblue: './icons/blue.png' };
var init = function() {
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
input = (document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
searchBox = new google.maps.places.SearchBox((input));
store.listener();
},
listener = function() {
google.maps.event.addListener(searchBox, 'places_changed', function() {
//search for places
var places = searchBox.getPlaces();
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
//set markers zero
markers = [];
$('.addaddress').empty();
//get new bounds
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
store.create_marker(place);
//append to the table
$('.addaddress').append('<tr><td>'+ place.name +'</td><td>'+ place.formatted_address +'</td><td>'+ place.formatted_phone_number +'</td><td>'+ place.website +'</td></tr>');
bounds.extend(place.geometry.location);
}
//set the map
map.fitBounds(bounds);
});
},
create_marker = function(info) {
//create a marker for each place
var marker = new google.maps.Marker({ map: map, icon: customIcons.iconblue, title: info.name, position: info.geometry.location });
//infowindow setup
google.maps.event.addListener(marker, "click", function() {
if (infowindow) {
infowindow.close();
}
infowindow = new google.maps.InfoWindow({content: info.name});
infowindow.open(map, marker);
});
//push the marker
markers.push(marker);
}
return {
init: init,
listener: listener,
create_marker: create_marker
};
})();
google.maps.event.addDomListener(window, 'load', store.init);
Google's API returns different place metadata, depending on which call you're using. To get more place details, you'll need to get the place's placeId and use that to make a call to place.getDetails()
Here's a more thorough answer: https://stackoverflow.com/a/9523345/2141296

Google Maps Api With Asp.net MVC 4 PartialView Ajax Request

I have a partial view. This partial view returns by Ajax.actionlink request. Partial View contain a google map . But map not rendering couse scripts must run when document is ready.
How to show google map in a partial view result ?
Partial View scripts :
var markers = [];
markercount = 0;
var zoom = 7;
var G = google.maps;
var map;
function initializeMap() {
var centerPoint = new G.LatLng(45.5, -100.5);
var myOptions = {
center: centerPoint,
zoom: zoom,
mapTypeId: G.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
myOptions);
addPolygon(map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
var input = (
document.getElementById('autocomplate'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
google.maps.event.addListener(map, 'click', addMarker);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
marker.setIcon(({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initializeMap);
I solved with this.
#Ajax.ActionLink(" ", "EditRestaurant", "Admin", New With {.RestID = Model(i).RestaurantID}, New AjaxOptions With {.HttpMethod = "POST",
.InsertionMode=InsertionMode.Replace,
.UpdateTargetId="edit",
.OnSuccess="map"}, New With {.Class = "glyphicon glyphicon-zoom-out"})
script
function map()
{
initializeMap();
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, 'load', initializeMap);
}

Google maps API geolocation + radar places search

I am trying to use both Geolocation and Places from the google maps API to display a map (at my location) with the nearest places around me. The two examples work seperately but not together.
Can anyone tell me why there is a problem with this? am I overwriting the map with another or doing something else wrong?
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyA93l5zPyIvGB7oYGqzLSk28r5XuIs2Do8
&sensor=true&libraries=places"></script>
<script>
var map;
var service;
var marker;
var pos;
function initialize() {
var mapOptions = {
zoom: 15
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Located'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
var request = {
location:pos,
radius:500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request,callback);
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
EDIT
Moved the code now so it looks like - Has not fixed the problem of location being undefined.
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var request = {
location:pos,
radius:500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request,callback);
pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Located'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});'
Because of async call to navigator.geolocation.getCurrentPosition() which returns immediately, location property of request is undefined. Call to
service.nearbySearch(request,callback);
complains that location is missing. And that is true because pos is not set at that moment.
You have to move this part of code:
var request = {
location:pos,
radius:500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request,callback);
to
navigator.geolocation.getCurrentPosition(function(position) {
...
map.setCenter(pos);
and make variable infoWindow global.
This is changed initialize() function:
var map;
var service;
var marker;
var pos;
var infowindow;
function initialize() {
var mapOptions = {
zoom: 15
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
console.log(map);
// Try HTML5 geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Located'
});
map.setCenter(pos);
var request = {
location:pos,
radius:500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request,callback);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
console.log('after / to createMarker');
createMarker(results[i]);
}
}
}
}

Google Places API (get all postal code around me)

I am using the blowing script to get all store around position wit 20 mile and working well but when try to using it to get postal_code do not working
how i get all postal code around center with specific distance
code:
<script type="text/javascript" language="javascript">
var lat = "";
var lng = "";
function latClick(glocation) {
var a = new google.maps.Geocoder();
a.geocode({ 'address': glocation }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK)
var c = results;
else
c = "We couldn't find that location. Please try again."
lat = c[0].geometry.location.lat();
lng = c[0].geometry.location.lng();
var pyrmont = new google.maps.LatLng(lat, lng);
//sll=30.04443,31.234217&sspn=0.036703,0.084543&geocode=FU1wygEdO5jcAQ%3BFQRxygEdgJ7cASnrviELpj9YFDG6O0LolrLfeQ&mra=mift&
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: 200,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
});
}
var map;
var infowindow;
function initialize() {
latClick("Jersey City, NJ 07306, United States");
}
function callback(results, status) {
var x = "";
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
x = x + results[i].name + ", ";
}
alert(x);
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>