How to get coordinates in polyline using google map? - google-maps

I tried to create a polyline in google Maps. It's created and polyline also working fine. but I need when to click polyline to get coordinates. My Scenario(I have three markers in google map.so, three markers used to connect the polyline markerA connect to markerB connect to markerC. when I click polyline in between markerA and makrerB. I need that two markers latitude and longitude). How to achieve this scenario.
My Code
<!DOCTYPE html>
<html>
<body>
<h1>My First Google Map</h1>
<div id="googleMap" style="width:100%;height:400px;"></div>
<script>
function myMap() {
var mapProp= {
center:new google.maps.LatLng(51.508742,-0.120850),
zoom:5,
};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
var goldenGatePosition = [{lat: 11.0168,lng: 76.9558},{lat: 11.6643,lng: 78.1460},{lat:11.2189,lng:78.1674}];
for(let i=0;i<goldenGatePosition.length;i++){
var marker = new google.maps.Marker({
position: goldenGatePosition[i],
map: map,
title: 'Golden Gate Bridge'
});
}
var flightPath = new google.maps.Polyline({
path:goldenGatePosition,
strokeColor:"#0000FF",
strokeOpacity:0.8,
strokeWeight:2
});
flightPath.setMap(map);
var infowindow = new google.maps.InfoWindow();
var codeStr=''
google.maps.event.addListener(flightPath, 'click', function(event) {
infowindow.setContent("content");
// var pathArr = flightPath.getPath()
// for (var i = 0; i < pathArr.length; i++){
// codeStr = '{lat: ' + pathArr.getAt(i).lat() + ', lng: ' + pathArr.getAt(i).lng() + '}' ;
// console.log(codeStr)
// };
console.log(event.latLng)
var length = this.getLength();
var mid = Math.round( length / 2 );
var pos = this.getAt( mid );
console.log(pos)
// infowindow.position = event.latLng;
infowindow.setPosition(event.latLng);
infowindow.open(map);
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCHmYOxkvd4u3rbHqalUSlGOa-b173lygA&callback=myMap"></script>
</body>
</html>
Google Map

Simplest way:
include the google maps geometry library.
use the poly namespace isLocationOnEdge method to detect which segment of the polyline the click was on. Output the two end coordinates of that segment.
isLocationOnEdge(point, poly[, tolerance])
Parameters:
point: LatLng
poly: Polygon|Polyline
tolerance: number optional
Return Value: boolean
Computes whether the given point lies on or near to a polyline, or the edge of a polygon, within a specified tolerance. Returns true when the difference between the latitude and longitude of the supplied point, and the closest point on the edge, is less than the tolerance. The tolerance defaults to 10-9 degrees.
google.maps.event.addListener(flightPath, 'click', function(event) {
// make polyline for each segment of the input line
for (var i = 0; i < this.getPath().getLength() - 1; i++) {
var segmentPolyline = new google.maps.Polyline({
path: [this.getPath().getAt(i), this.getPath().getAt(i + 1)]
});
// check to see if the clicked point is along that segment
if (google.maps.geometry.poly.isLocationOnEdge(event.latLng, segmentPolyline,10e-3)) {
// output the segment number and endpoints in the InfoWindow
var content = "segment "+i+"<br>";
content += "start of segment=" + segmentPolyline.getPath().getAt(0).toUrlValue(6) + "<br>";
content += "end of segment=" + segmentPolyline.getPath().getAt(1).toUrlValue(6) + "<br>";
infowindow.setContent(content);
infowindow.setPosition(event.latLng);
infowindow.open(map);
}
}
});
proof of concept fiddle
code snippet:
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#googleMap {
height: 80%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<h1>My First Google Map</h1>
<div id="googleMap"></div>
<script>
function myMap() {
var mapProp = {
center: new google.maps.LatLng(51.508742, -0.120850),
zoom: 5,
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var goldenGatePosition = [{
lat: 11.0168,
lng: 76.9558
}, {
lat: 11.6643,
lng: 78.1460
}, {
lat: 11.2189,
lng: 78.1674
}];
var bounds = new google.maps.LatLngBounds();
for (let i = 0; i < goldenGatePosition.length; i++) {
var marker = new google.maps.Marker({
position: goldenGatePosition[i],
map: map,
title: 'Golden Gate Bridge'
});
bounds.extend(goldenGatePosition[i]);
}
var flightPath = new google.maps.Polyline({
path: goldenGatePosition,
strokeColor: "#0000FF",
strokeOpacity: 0.8,
strokeWeight: 2
});
flightPath.setMap(map);
map.fitBounds(bounds);
var infowindow = new google.maps.InfoWindow();
var codeStr = ''
google.maps.event.addListener(flightPath, 'click', function(event) {
// make polyline for each segment of the input line
for (var i = 0; i < this.getPath().getLength() - 1; i++) {
var segmentPolyline = new google.maps.Polyline({
path: [this.getPath().getAt(i), this.getPath().getAt(i + 1)]
});
// check to see if the clicked point is along that segment
if (google.maps.geometry.poly.isLocationOnEdge(event.latLng, segmentPolyline, 10e-3)) {
// output the segment number and endpoints in the InfoWindow
var content = "segment " + i + "<br>";
content += "start of segment=" + segmentPolyline.getPath().getAt(0).toUrlValue(6) + "<br>";
content += "end of segment=" + segmentPolyline.getPath().getAt(1).toUrlValue(6) + "<br>";
infowindow.setContent(content);
infowindow.setPosition(event.latLng);
infowindow.open(map);
}
}
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=myMap"></script>

Related

Google Maps MarkerClusterer not showing any default images

I'm adding javascript code snippet to my Wordpress post (Hosted by a 3rd Party). I managed to create an array of Markers, and had them added to the MarkerClusterer and Map. The cluster shows up but as a broken image link and a number.
How do I access the MarkerClusterer default images? I followed the instructions from https://github.com/googlemaps/js-markerclusterer/blob/main/README.md
I'm not sure how to use npm with the 3rd party hosting. I don't use a database with my website. I'm calling src="https://unpkg.com/#googlemaps/markerclusterer/dist/index.min.js" to import MarkerClusterer
<div id="gmap" style="width:100%;height:400px;"></div>
<script src="https://unpkg.com/#googlemaps/markerclusterer/dist/index.min.js"</script>
var mymap;
var markers = [];
function initMap() {
var centerpoint = { lat: 38.5, lng: -98 }; //centered around Kansas
mymap = new google.maps.Map(document.getElementById('gmap'), {
zoom: 4,
center: centerpoint
});
}
/** fetching a cvs file on the server side with a list of locations */
fetch("https://mywebsite.com/wp-content/uploads/2022/03/stores.csv")
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.text().then(function(data) {
count = 0;
console.log("fetch called successfully");
initMap();
processCSV(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
function processCSV(allData){
const rows = allData.split('\n');
var storename, storephone, storeaddress, storelat, storelng;
for(let i=0; i<rows.length; i++){
var line = rows[i];
storename = line.split(",")[1];
storephone = line.split(",")[3];
storeaddress = String(line.split(",")[2]);
storeaddress = replaceAll(storeaddress, "^", ",");
storelat = line.split(",")[4];
storelng = line.split(",")[5];
createMarker(storename, storephone, storeaddress, storelat, storelng);
}
createCluster();
}
function replaceAll(string, search, replace) {
return string.split(search).join(replace);
}
function createCluster(){
var mcluster =new MarkerClusterer( mymap , markers);
}
function createMarker(name, phone, address, latstr, lngstr) {
var contentString = "<b>" + name + "</b><br><br><i>" + phone + "</i><br><br>" + address;
var latLng = { lat: Number(latstr) , lng: Number(lngstr)};
var infowindow = new google.maps.InfoWindow({
content: contentString,
});
var marker = new google.maps.Marker({
position: latLng,
map: mymap,
title: name
});
markers.push(marker);
console.log("added marker to map" + name);
marker.addListener("click", () => {
infowindow.open({
anchor: marker,
map: mymap,
shouldFocus: false,
});
});
}
<script src="https://maps.googleapis.com/maps/api/js?key=<PRIVATEKEY>;callback=initMap"></script>
The version of MarkerClusterer you are using doesn't require ClusterIcons (unless you want to change them), they default to SVG icons coded inline.
When I run the posted code I get a javascript error: Uncaught (in promise) ReferenceError: MarkerClusterer is not defined.
That is because according to the documentation when you include the library the way you are (<script src="https://unpkg.com/#googlemaps/markerclusterer/dist/index.min.js"></script>), the constructor for the MarkerClusterer is accessed as:
When adding via unpkg, the MarkerClusterer can be accessed at markerClusterer.MarkerClusterer.
Changing that, makes the clusters appear.
proof of concept fiddle
code snippet:
var mymap;
var markers = [];
function initMap() {
var centerpoint = {
lat: 40.7127753,
lng: -74.0059728
}; //centered around New York City
mymap = new google.maps.Map(document.getElementById('gmap'), {
zoom: 4,
center: centerpoint
});
processCSV(data);
}
var data = '"","New York","New York^ NY","516-555-5555",40.7127753, -74.0059728\n"","Newark","Newark^ NJ","201-555-5555",40.735657, -74.1723667';
function processCSV(allData) {
console.log(allData);
const rows = allData.split('\n');
var storename, storephone, storeaddress, storelat, storelng;
for (let i = 0; i < rows.length; i++) {
var line = rows[i];
storename = line.split(",")[1];
storephone = line.split(",")[3];
storeaddress = String(line.split(",")[2]);
storeaddress = replaceAll(storeaddress, "^", ",");
storelat = line.split(",")[4];
storelng = line.split(",")[5];
createMarker(storename, storephone, storeaddress, storelat, storelng);
}
createCluster();
}
function replaceAll(string, search, replace) {
return string.split(search).join(replace);
}
function createCluster() {
var mcluster = new markerClusterer.MarkerClusterer({
map: mymap,
markers: markers
});
}
function createMarker(name, phone, address, latstr, lngstr) {
var contentString = "<b>" + name + "</b><br><br><i>" + phone + "</i><br><br>" + address;
var latLng = {
lat: Number(latstr),
lng: Number(lngstr)
};
var infowindow = new google.maps.InfoWindow({
content: contentString,
});
var marker = new google.maps.Marker({
position: latLng,
map: mymap,
title: name
});
markers.push(marker);
console.log("added marker to map" + name);
marker.addListener("click", () => {
infowindow.open({
anchor: marker,
map: mymap,
shouldFocus: false,
});
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#gmap {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="gmap"></div>
<script src="https://unpkg.com/#googlemaps/markerclusterer/dist/index.min.js"></script>
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&v=weekly&channel=2" async></script>
</body>
</html>

How to assign info window in polyline using google map api

My Scenario. I have five markers and connecting to the polyline. When I click marker a to marker b between polyline it will show an info window. In the info, the window has marker a address and marker b address. I achieved this scenario using islocationedge concept in google Maps API. but this concept I facing an issue. when I click marker a to marker b polyline it will show marker b and marker c address because segment polyline I used. I need how to assign an info window in an individual polyline.
My code
<!DOCTYPE html>
<html>
<body>
<h1>My First Google Map</h1>
<div id="googleMap" style="width:100%;height:400px;"></div>
<script>
function myMap() {
var mapProp= {
center:new google.maps.LatLng(51.508742,-0.120850),
zoom:5,
};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
var goldenGatePosition = [{lat: 30.2179130,lng: -81.5628150, address: 'Tamil Nadu'},{lat: 30.2179140,lng: -81.5627480, address: 'India'},{lat:30.2177650,lng:-81.5629100,address: 'America'},{lat: 30.2844080,lng: -81.5633900, address: 'Tamil Nadu'},{lat: 30.2843840,lng: -81.5633890, address: 'Tamil Nadu'}];
for(let i=0;i<goldenGatePosition.length;i++){
var marker = new google.maps.Marker({
position: goldenGatePosition[i],
map: map,
title: 'Golden Gate Bridge'
});
}
var flightPath = new google.maps.Polyline({
path:goldenGatePosition,
strokeColor:"#0000FF",
strokeOpacity:0.8,
strokeWeight:2
});
flightPath.setMap(map);
let poly, geodesicPoly;
var infowindow = new google.maps.InfoWindow();
var codeStr=''
google.maps.event.addListener(flightPath, 'click', function(event) {
// make polyline for each segment of the input line
for (var i = 0; i < this.getPath().getLength() - 1; i++) {
var segmentPolyline = new google.maps.Polyline({
path: [this.getPath().getAt(i), this.getPath().getAt(i + 1)]
});
console.log(segmentPolyline)
// check to see if the clicked point is along that segment
if (google.maps.geometry.poly.isLocationOnEdge(event.latLng, segmentPolyline, 10e-3)) {
console.log(' I ', i)
// output the segment number and endpoints in the InfoWindow
var origin = new Array()
var destination = new Array()
console.log('****************')
for(let i=0;i<goldenGatePosition.length; i++){
console.log(goldenGatePosition[i])
}
console.log('****************')
console.log(segmentPolyline.getPath().getAt(0).address)
origin.push(segmentPolyline.getPath().getAt(0).toUrlValue(6))
destination.push(segmentPolyline.getPath().getAt(1).toUrlValue(6))
const service = new google.maps.DistanceMatrixService(); // instantiate Distance Matrix service
const matrixOptions = {
origins: origin, // technician locations
destinations: destination, // customer address
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.IMPERIAL
};
// Call Distance Matrix service
service.getDistanceMatrix(matrixOptions, callback);
// Callback function used to process Distance Matrix response
function callback(response, status) {
console.log(response)
console.log(status)
if (status !== "OK") {
alert("Error with distance matrix");
return;
}
console.log(response);
}
var content = "segment " + i + "<br>";
content += "start of segment=" + segmentPolyline.getPath().getAt(0).toUrlValue(6) + "<br>";
content += "end of segment=" + segmentPolyline.getPath().getAt(1).toUrlValue(6) + "<br>";
infowindow.setContent(content);
infowindow.setPosition(event.latLng);
infowindow.open(map);
}
}
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAiybKuHI544-t5XPZzBGjQOBCO4MZFCwM&callback=myMap&libraries=geometry"></script>
</body>
</html>
When i click the polyline. How to get marker coordinates from polyline one end to another end.
The tolerance in your call to isLocationOnEdge is too small.
isLocationOnEdge
isLocationOnEdge(point, poly[, tolerance])
Parameters:
point: LatLng
poly: Polygon|Polyline
tolerance: number optional
Return Value:* boolean
Computes whether the given point lies on or near to a polyline, or the edge of a polygon, within a specified tolerance. Returns true when the difference between the latitude and longitude of the supplied point, and the closest point on the edge, is less than the tolerance. The tolerance defaults to 10-9 degrees.
Your code:
if (google.maps.geometry.poly.isLocationOnEdge(event.latLng, segmentPolyline, 10e-3)) {
Working value:
if (google.maps.geometry.poly.isLocationOnEdge(event.latLng, segmentPolyline, 10e-7)) {
(when it is too large, it is picking up segment 1 for all locations on segment 0, as far as I can tell, all the other segments work correctly with your value)
proof of concept fiddle
code snippet:
function myMap() {
var mapProp = {
center: new google.maps.LatLng(51.508742, -0.120850),
zoom: 5,
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var bounds = new google.maps.LatLngBounds();
for (let i = 0; i < goldenGatePosition.length; i++) {
var marker = new google.maps.Marker({
position: goldenGatePosition[i],
map: map,
title: goldenGatePosition[i].address
});
if (i == 0 || i == 1) bounds.extend(marker.getPosition());
}
map.fitBounds(bounds);
var flightPath = new google.maps.Polyline({
path: goldenGatePosition,
strokeColor: "#0000FF",
strokeOpacity: 0.8,
strokeWeight: 2
});
flightPath.setMap(map);
let poly, geodesicPoly;
var infowindow = new google.maps.InfoWindow();
var codeStr = ''
google.maps.event.addListener(flightPath, 'click', function(event) {
// make polyline for each segment of the input line
for (var i = 0; i < this.getPath().getLength() - 1; i++) {
var segmentPolyline = new google.maps.Polyline({
path: [this.getPath().getAt(i), this.getPath().getAt(i + 1)]
});
console.log(segmentPolyline)
// check to see if the clicked point is along that segment
if (google.maps.geometry.poly.isLocationOnEdge(event.latLng, segmentPolyline, 10e-7)) {
console.log(' I ', i)
// output the segment number and endpoints in the InfoWindow
var origin = new Array()
var destination = new Array()
console.log('****************')
for (let i = 0; i < goldenGatePosition.length; i++) {
console.log(goldenGatePosition[i])
}
console.log('****************')
console.log(segmentPolyline.getPath().getAt(0).address)
origin.push(segmentPolyline.getPath().getAt(0).toUrlValue(6))
destination.push(segmentPolyline.getPath().getAt(1).toUrlValue(6))
const service = new google.maps.DistanceMatrixService(); // instantiate Distance Matrix service
const matrixOptions = {
origins: origin, // technician locations
destinations: destination, // customer address
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.IMPERIAL
};
// Call Distance Matrix service
service.getDistanceMatrix(matrixOptions, callback);
console.log("break")
// Callback function used to process Distance Matrix response
function callback(response, status) {
console.log(response)
console.log(status)
if (status !== "OK") {
alert("Error with distance matrix");
return;
}
console.log(response);
}
var content = "segment " + i + "<br>";
content += "start of segment=" + segmentPolyline.getPath().getAt(0).toUrlValue(6) + "<br>";
content += "end of segment=" + segmentPolyline.getPath().getAt(1).toUrlValue(6) + "<br>";
infowindow.setContent(content);
infowindow.setPosition(event.latLng);
infowindow.open(map);
}
}
});
}
var goldenGatePosition = [{
lat: 30.2179130,
lng: -81.5628150,
address: 'Tamil Nadu'
}, {
lat: 30.2179140,
lng: -81.5627480,
address: 'India'
}, {
lat: 30.2177650,
lng: -81.5629100,
address: 'America'
}, {
lat: 30.2844080,
lng: -81.5633900,
address: 'Tamil Nadu'
}, {
lat: 30.2843840,
lng: -81.5633890,
address: 'Tamil Nadu'
}];
html,
body,
#googleMap {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
}
<div id="googleMap"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=myMap&libraries=geometry" defer></script>

Google maps get position of an marker

I am adding multiple markers, and what I want to do is on click, get that specific marker position.
However at the moment it does work however it displays lat and lng for the last marker created. How can this be solved so that when I click on the marker it will give me that specific position of that marker.
function algolia_search(position) {
clearOverlays();
var APPLICATION_ID = '75RQSC1OHE';
var SEARCH_ONLY_API_KEY = 'f2f1e9bba4d7390fc61523a04685cf12';
var INDEX_NAME = 'businesses';
var PARAMS = { hitsPerPage: 20 };
// Client + Helper initialization
var algolia = algoliasearch(APPLICATION_ID, SEARCH_ONLY_API_KEY);
var algoliaHelper = algoliasearchHelper(algolia, INDEX_NAME, PARAMS);
// Map initialization
algoliaHelper.on('result', function(content) {
renderHits(content);
var i;
// Add the markers to the map
for (i = 0; i < content.hits.length; ++i) {
var hit = content.hits[i];
var marker = new google.maps.Marker({
position: {lat: hit._geoloc.lat, lng: hit._geoloc.lng},
map: map,
label: hit._geoloc.slug,
animation: google.maps.Animation.DROP
});
markers.push(marker);
marker.addListener('click', function() {
var destinationLat = marker.getPosition().lat();
var destinationLng = marker.getPosition().lng();
console.log(lat);
console.log(lng);
console.log(destinationLat);
console.log(destinationLng);
you need a listerner on map for click in event.latLng you have coordinates
google.maps.event.addListener(map, 'click', function(event) {
alert ( 'Lat : ' + event.latLng.lat() + ' Lng : ' + event.latLng.lng())
});
do the fact you have already place the marker on maps you could use a closure
var addListenerOnPoint = function(actMark){
actMark.addListener('click', function() {
alert ( 'Lat : ' + actMark.position.lat() + ' Lng : ' +actMark.position.lng());
});
for (i = 0; i < content.hits.length; ++i) {
var hit = content.hits[i];
var marker = new google.maps.Marker({
position: {lat: hit._geoloc.lat, lng: hit._geoloc.lng},
map: map,
label: hit._geoloc.slug,
animation: google.maps.Animation.DROP
});
addListenerOnPoint(marker,
);
markers.push(marker);
}

Google maps v3 - Add markers at the center of tiles

function initialize() {
var myLatlng;
var mapOptions;
myLatlng = new google.maps.LatLng(29.98439980, -95.34140015);
mapOptions = {
zoom: 16,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(
document.getElementById("map-canvas"), mapOptions);
google.maps.event.addListenerOnce(map, 'idle', function() {
drawRectangle(map);
var result = {"regionList":[{"centerLongitude":-95.34890747070312,"imageIcon":"../images/untested-icon.png","centerLatitude":29.980682373046875},{"centerLongitude":-95.34890747070312,"imageIcon":"../images/untested-icon.png","centerLatitude":29.988117218017578},{"centerLongitude":-95.33389282226562,"imageIcon":"../images/untested-icon.png","centerLatitude":29.980682373046875},{"centerLongitude":-95.33389282226562,"imageIcon":"../images/untested-icon.png","centerLatitude":29.988117218017578}]};
alert(result);
addMarkersAtRegionCenter(map, result);
});
function addMarkersAtRegionCenter(map, result) {
var length = result.regionList.length;
var regionUrl = "drilledDownToRegion.jsp?";
for(var i=0; i<length; i++)
{
var image = result.regionList[i].imageIcon;
//alert("Latitude : " + result.regionList[i].centerLatitude);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(result.regionList[i].centerLatitude,result.regionList[i].centerLongitude),
icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() {
window.location.href = marker.url;
}
})(marker, i));
}
}
function drawRectangle(map) {
var bounds = map.getBounds();
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();
var numberOfParts = 4;
var tileWidth = (northEast.lng() - southWest.lng()) / numberOfParts;
var tileHeight = (northEast.lat() - southWest.lat()) / numberOfParts;
for (var x = 0; x < numberOfParts; x++) {
for (var y = 0; y < numberOfParts; y++) {
var areaBounds = {
north: southWest.lat() + (tileHeight * (y+1)),
south: southWest.lat() + (tileHeight * y),
east: southWest.lng() + (tileWidth * (x+1)),
west: southWest.lng() + (tileWidth * x)
};
var area = new google.maps.Rectangle({
strokeColor: '#FF0000',
//strokeOpacity: 0.8,
strokeWeight: 2,
//fillColor: '#FF0000',
//fillOpacity: 0.35,
map: map,
bounds: areaBounds
});
}
}
}
}
google.maps.event.addDomListener(window, "load", initialize);
In the above code, I am trying to add markers at the center of each rectangle. But I am not able to add markers. I have hard coded image icon value since I don't have image mentioned in the array.
Thanks in advance for your help.
Related question: Google maps api v3 - divide region into equal parts using tiles
Simpler to add the markers to the centers of the rectangles when you create them:
var centerMark = new google.maps.Marker({
position: area.getBounds().getCenter(),
map: map
});
proof of concept fiddle
To add the markers from the response to the map (the positions in the posted response are not at the center of the squares), this is the same function you posted in your question, it works for me (the blue markers), I modified your click listener to open an infowindow (rather than do a redirect of the page):
function addMarkersAtRegionCenter(map, result) {
var length = result.regionList.length;
var regionUrl = "drilledDownToRegion.jsp?";
for (var i = 0; i < length; i++) {
var image = result.regionList[i].imageIcon;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(result.regionList[i].centerLatitude, result.regionList[i].centerLongitude),
icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
// window.location.href = marker.url;
infowindow.setContent("regionList:" + i + "<br>centLat=" + result.regionList[i].centerLatitude + "<br>centLng=" + result.regionList[i].centerLongitude + "<br>imageIcon=" + result.regionList[i].imageIcon + "<br>" + marker.getPosition().toUrlValue(6));
infowindow.open(map, marker);
}
})(marker, i));
}
}

Google maps v3 decode polygon(s) from MySQL database

I would like to draw one or more polygons which are saved encoded in the MySQL database. I've based my code on the known bermudatriangle script example. The XML from "polygon_xml.php" is OK. For now, there's only 1 encoded coordinate in the database. At: //alert1(decodedPolygon); the coordinates are shown, but at //alert2(decodedPolygon); it's not. It has something to do with the array decodedPolygon I guess. What makes me more confusing is that the polygon does show when I uncomment //alert2(decodedPolygon);. Alert2 is empty but after clicking "OK", the polygon is shown on the map!??? Finally I would like to add text to the XML and place it in the infowindow instead of the coordinates.
My 3 encoded coordinates are:
{zzfIsjmu#kHuczRrg{NxcsO}t{GtczR
a}~cIqcskBu|sEov{OoxNel}AfccMwfzG~q|#nknX}u~GvczR
cljkHmfoQl|J{hrV~syGzhrV
I hope somebody can help / explain.
Here's my code so far:
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry">
<script>
var map;
var infoWindow;
var decodedPolygon = [];
function initialize() {
var mapOptions = {
zoom: 3,
center: new google.maps.LatLng(49.724479, 17.578125),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
downloadUrl("polygon_xml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
//var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
var encodedPath = markers[i].getAttribute("coords");
decodedPolygon = google.maps.geometry.encoding.decodePath(encodedPath);
//alert1(decodedPolygon);
//bounds.extend(decodedPolygon);
}
})
//alert2(decodedPolygon);
// Construct the polygon.
bermudaTriangle = new google.maps.Polygon({
paths: decodedPolygon,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FF0000',
fillOpacity: 0.35
});
bermudaTriangle.setMap(map);
// Add a listener for the click event.
google.maps.event.addListener(bermudaTriangle, 'click', showArrays);
infoWindow = new google.maps.InfoWindow();
}
/** #this {google.maps.Polygon} */
function showArrays(event) {
// Since this polygon has only one path, we can call getPath()
// to return the MVCArray of LatLngs.
var vertices = this.getPath();
var contentString = '<b>Bermuda Triangle polygon</b><br>' +
'Clicked location: <br>' + event.latLng.lat() + ',' + event.latLng.lng() +
'<br>';
// Iterate over the vertices.
for (var i = 0; i < vertices.getLength(); i++) {
var xy = vertices.getAt(i);
contentString += '<br>' + 'Coordinate ' + i + ':<br>' + xy.lat() + ',' +
xy.lng();
}
// Replace the info window's content and position.
infoWindow.setContent(contentString);
infoWindow.setPosition(event.latLng);
infoWindow.open(map);
}
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('GET', url, true);
request.send(null);
}
function doNothing() {}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<body>
<div id="map-canvas"></div>
downloadUrl is asynchronous, you need to use the data returned inside the callback routine. Right now, the bermudaTriangle polygon is constructed before the data is returned (outside of the callback function).
function initialize() {
var mapOptions = {
zoom: 3,
center: new google.maps.LatLng(49.724479, 17.578125),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
downloadUrl("polygon_xml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
var encodedPath = markers[i].getAttribute("coords");
var decodedPolygon = google.maps.geometry.encoding.decodePath(encodedPath);
for (var j = 0; j < decodedPolygon.length; j++) {
bounds.extend(decodedPolygon[j]);
}
// Construct the polygon.
var bermudaTriangle = new google.maps.Polygon({
paths: decodedPolygon,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FF0000',
fillOpacity: 0.35
});
bermudaTriangle.setMap(map);
// Add a listener for the click event.
google.maps.event.addListener(bermudaTriangle, 'click', showArrays);
}
map.fitBounds(bounds);
})
infoWindow = new google.maps.InfoWindow();
}
proof of concept fiddle