I'm new to google maps api ,i'm trying to draw polygons using google maps api , I want to show the project of the polygon and that project polygon above (inside) allow to draw the building polygon.
I'm trying to clear all my polygon objects before I import new geoJSON data and create new objects.I can't seem to get the setMap(null) function to work correctly. Hopefully someone can kindly let me know where I am failing.
demo
<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=geometry,places&sensor=true"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<input type="hidden" id="center_point" value="12.939884,77.62540710000007" />
<input type="hidden" id="projectPolygon" value="" />
<input type="hidden" id="autocompleteLat" value="12.939884" />
<input type="hidden" id="autocompleteLng" value="77.62540710000007" />
<input type="hidden" id="poly_map_codes" value="" />
<input type="hidden" id="zoom_level" value="18" />
<textarea id="xml_valuesMain" style="display:none;">[{"source":"project","latlng":[{"lat":"12.940573081014005","lng":"77.62384235858917"},{"lat":"12.940656731834343","lng":"77.62625098228455"},{"lat":"12.939532671591135","lng":"77.6263153553009"},{"lat":"12.939564040782932","lng":"77.62391209602356"}]}]</textarea>
<textarea id="xml_values" style="display:none;">[{"source":"project","latlng":[{"lat":"12.940573081014005","lng":"77.62384235858917"},{"lat":"12.940656731834343","lng":"77.62625098228455"},{"lat":"12.939532671591135","lng":"77.6263153553009"},{"lat":"12.939564040782932","lng":"77.62391209602356"}]}]</textarea>
<div id="init_map" style="height: 600px;"></div>
<script>
$(function(){
initMap();
});
function initMap()
{
var polygons = [];
var coordinates = [];
var markers=[];
var latt=$('#autocompleteLat').val();
var lngg=$('#autocompleteLng').val();
var amsterdam = new google.maps.LatLng(latt,lngg);
var zoom_level=parseInt($('#zoom_level').val());
var map = new google.maps.Map(document.getElementById('init_map'),{ center: amsterdam, zoom: zoom_level, mapTypeId:google.maps.MapTypeId.SATELLITE });
drawSecondPolygon();
function drawSecondPolygon()
{
google.maps.event.trigger(map, 'refresh');
var data =$('#xml_values').val();
var jsonData = JSON.parse(data);
var polygons = [];
console.log("polygon length="+polygons.length);
for( var i = 0; i < polygons.length; i++ )
{
polygons[i].setMap(null)
}
polygons.length = 0;
for (var i = 0; i < jsonData.length; i++)
{
var latArr = jsonData[i].latlng;
var source_d = jsonData[i].source;
arr = [];
for(j=0; j<latArr.length;j++)
{
var lat=latArr[j].lat;
var lng=latArr[j].lng;
arr.push(new google.maps.LatLng(parseFloat(lat),parseFloat(lng)));
}
if(source_d=="project") { var FillColor='#DA70D6'; var StrokeColr='#BA55D3'; var editval=false; }
else if(source_d=="tower") { var FillColor='#FF8800'; var StrokeColr='#FF8800'; var editval=true; }
else if(source_d=="amenity") { var FillColor='#990000'; var StrokeColr='#990000'; var editval=false; }
else { var FillColor='#66FF00'; var StrokeColr='#66FF00'; var editval=false; }
polygons.push(new google.maps.Polygon({
paths: arr,
Source:source_d,
strokeColor: StrokeColr,
strokeOpacity: 0.8,
strokeWeight: 2,
editable:editval,
clickable:true,
fillColor: FillColor,
fillOpacity: 0.35
}));
console.log("polygons.length="+polygons.length);
polygons[polygons.length-1].setMap(null);
polygons[polygons.length-1].setMap(map);
if(editval==false)
{
console.log("Something working fine");
google.maps.event.addListener(polygons[polygons.length-1], 'click', function (clickEvent)
{
polygons[polygons.length-1].setMap(null);
var newLatLng=$('#poly_map_codes').val();
var clickEventLat=clickEvent.latLng.lat();
var clickEventLng=clickEvent.latLng.lng();
if(newLatLng!='') { newLatLng+=","+clickEventLat+" "+clickEventLng; }
else { newLatLng+=clickEventLat+" "+clickEventLng; }
$('#poly_map_codes').val(newLatLng);
//console.log(newLatLng);
//drawSecondPolygon();
if(newLatLng)
{
var getLatLng=newLatLng;
var getLatLngArr=getLatLng.split(",");
var main_LatLngArr=[];
for(i=0; i<getLatLngArr.length; i++)
{
var my_object={};
var getLatLngExp=getLatLngArr[i].split(" ");
my_object.lat=getLatLngExp[0];
my_object.lng=getLatLngExp[1];
main_LatLngArr.push(my_object);
}
var LatLngObj={};
LatLngObj.source="tower";
LatLngObj.latlng=main_LatLngArr;
var oldPolyArr=$('#xml_valuesMain').val();
var oldPolyArr=JSON.parse(oldPolyArr);
oldPolyArr.push(LatLngObj);
$('#xml_values').val(JSON.stringify(oldPolyArr));
polygons[polygons.length-1].setMap(null);
drawSecondPolygon();
console.log("oldPolyArr="+JSON.stringify(oldPolyArr));
}
});
}
}
}
}
</script>
At a first look you redeclare the var polygons = []; in your drawSecondPolygon function this override the content of the same variable declared in initMap ..
thi comment this line .. so you can use always the parent polygons array
function drawSecondPolygon()
{
google.maps.event.trigger(map, 'refresh');
var data =$('#xml_values').val();
var jsonData = JSON.parse(data);
//var polygons = [];
Related
I am having issues displaying data from localStorage into my HTML page, when I open the console the data is been saved, the issue is with innerhtml.
Below is both my html and JS code.
When i run the console, I can see that my data is saved on localStorage, the issue is inputing that data into the page
Here is my html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Fizzle</title>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css"
integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65"
crossorigin="anonymous"
/>
<link rel="stylesheet" href="css/style.css" />
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
</head>
<body class="">
<div class="row">
<div class="col">
<ul class="workouts">
<section class="weather">
<div id="today-container">
<div class="current-weather">
<h3 class="brand">the weather</h3>
</div>
<div>
<h1 class="temp">16°</h1>
<div class="city-time">
<h1 class="name">London</h1>
<small>
<span class="date">Monday Sep 19</span>
</small>
</div>
</div>
</section>
<form class="form hidden">
<div class="form__row">
<label class="form__label">Type</label>
<select class="form__input form__input--type">
<option value="running">Running</option>
<option value="cycling">Cycling</option>
</select>
</div>
<div class="form__row">
<label class="form__label">Distance</label>
<input id="distance-input"
class="form__input form__input--distance"
placeholder="km"
/>
</div>
<div class="form__row">
<label class="form__label">Duration</label>
<input id="duration-input"
class="form__input form__input--duration"
placeholder="min"
/>
</div>
<div class="form__row">
<label class="form__label">Elevation</label>
<input id ="elevation-input"
class="form__input form__input--cadence"
placeholder="meters"
/>
</div>
<button class="form__btn">OK</button>
</form>
</ul>
</div>
<div class="col">
<div id="map"></div>
</div>
<p> <h4 class="ElementThatHoldsTheHistoryData"></h4></p>
</div>
<div id="floating-panel"></div>
<div id="sidebar"></div>
<script
src="https://maps.googleapis.com/maps/api/js?key=API Key here"
defer>
</script>
<!-- <script async defer src="https://maps.googleapis.com/maps/api/js?key=APIkey here=initMap&libraries=geometry"></script> -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
Here is my JS code:
enter code her/Get all necessary elements from the DOM
const temp = document.querySelector(".temp");
const dateOutput = document.querySelector(".date");
const timeOutput = document.querySelector(".time");
const distance = document.querySelector("#distance-input");
const duration = document.querySelector("#duration-input");
const elevation = document.querySelector(".form__input--elevation");
const todayContainer = document.querySelector("#today-container");
// set my variables
var currentWeather = document.querySelector(".current-weather");
var APIkey = "&appid=99d1a7e58f500ed377f1399b47f88c6a";
var distanceInput = document.getElementById("distance-input");
var durationInput = document.getElementById("duration-input");
var elevationInput = document.getElementById("elevation-input");
var map;
var markers = [];
var directionsService;
var directionsRenderer;
var workoutElements = document.getElementsByClassName("workout");
var btn = document.querySelector(".form__btn");
//Default city when the page loads/------------------------------------------------------------
let cityInput = "London";
/// Get date /----------------------------------------------------------------------------------------------------------------
const date = moment().format("h:mm a - dddd MMM YY");
dateOutput.innerText = date;
// console.log(date);
// Google map
// map code with 2 markers and directions-----working code------------------------
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: 51.509865, lng: -0.118092 }, //center mapp to Hyde park London
zoom: 12.5,
});
directionsService = new google.maps.DirectionsService();
directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setMap(map);
directionsRenderer.setOptions({
polylineOptions: {
strokeColor: "red",
},
suppressMarkers: true,
});
// Add a click event listener to the map
google.maps.event.addListener(map, "click", function (event) {
addMarker(event.latLng);
});
}
function addMarker(location) {
// Add the marker at the clicked location
var marker = new google.maps.Marker({
position: location,
map: map,
});
markers.push(marker);
if (markers.length >= 2) {
calculateAndDisplayRoute();
}
}
function deleteMarkers() {
// Clear markers from the map
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
}
//function to add distance and duration:
function calculateAndDisplayRoute() {
var request = {
origin: markers[0].getPosition(),
destination: markers[1].getPosition(),
travelMode: "BICYCLING",
provideRouteAlternatives: true,
unitSystem: google.maps.UnitSystem.METRIC,
};
directionsService.route(request, function (response, status) {
if (status === "OK") {
directionsRenderer.setDirections(response);
var distance = response.routes[0].legs[0].distance.text;
var duration = response.routes[0].legs[0].duration.text;
var elevation = response.routes[0].legs[0].elevation;
// set input values
document.getElementById("distance-input").value = distance;
document.getElementById("duration-input").value = duration;
document.getElementById("elevation-input").value = elevation;
} else {
window.alert("Directions request failed due to " + status);
}
});
}
function getLocation() {
navigator.geolocation.getCurrentPosition((data) => {
const lat = data.coords.latitude;
const lon = data.coords.longitude;
initMap(lat, lon);
currentConditions(lat, lon);
});
}
//Weather
//fetch data from current weather api, and display desired data on the page
function currentConditions(lat, lon) {
let currentWeatherAPI = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}${APIkey}&units=metric`;
const tempDisplay = document.querySelector(".temp");
const cityname = document.querySelector(".name");
fetch(currentWeatherAPI)
.then(function (response) {
return response.json();
})
.then(function (wdata) {
// city's name, and use moment to get the date
// var city = getLocation();
// weather condition icon
var weatherIcon = wdata.weather[0].icon;
//add
tempDisplay.innerText = Math.round(wdata.main.temp) + "°";
cityname.innerText = wdata.name;
});
}
getLocation();
// local storage
btn.addEventListener("click", function (event) {
event.preventDefault();
// Clear form
distance.value = "";
duration.value = "";
// Clear markers from the map
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
var rides = JSON.parse(localStorage.getItem("rides")) || []; // Add new ride to existing rides data in LS
var newRide = { distance: distance.value, duration: duration.value };
rides.push(newRide);
localStorage.setItem("rides", JSON.stringify(rides));
// for loop to iterate through the collection of elements and set the innerHTML property of each element to the stored data.
var element = document.querySelector("ElementThatHoldsTheHistoryData");
for (let i = 0; i < rides.length; i++) {
var h4 = document.createElement("p");
h4.textContent = `The Distance was ${rides[i].distance} and the Duration was ${rides[i].duration}`;
element.appendChild(h4);
}});
Arrange your p tag like this
const h4 = `<p>The Distance was ${rides[i].distance} and the Duration was ${rides[i].duration}</p>`
Instead of document.querySelector I would prefer to use getElementById or className
document.getElementById('question-header').append(h4)
Finally, append your HTML to the Id
I have to select a marker in a map based on the button click. I have multiple marker with each marker associated to button below. I want to change "myloc" on that button click and by default it must select 13, 100.
Html
<div class="row">
<input type="button" id="btn-first" class="btn-a" value = "First">
<input type="button" id="btn-second" class="btn-a" value = "Second">
</div>
JS
let myloc = new L.LatLng(13, 100);
var map = L.map('map').setView(myloc, 12);
$(function () {
$('.btn-a').on('click', function(e){
e.preventDefault();
var clsName = $(this).val();
var lat, long;
if (clsName == 'First') {
lat = 13;
long = 100;
} else if(clasName = 'Second') {
lat = 14;
long = 101;
}
})
});
I dont see you setting the myLoc object anywhere. You are just assigning value for lat, lng. Check the snippet below to see if it answers your question.
Here, you initiliaze myLoc and on button click get new values for lat, lng and set it at the end again for myLoc
//just a temp function to show the example. Dont add this in your code
var L = {
LatLng: function(lat, lng) {
console.log("Current Values for Lat, Lng: " + lat + " , "+ lng);
}
}
let myloc = new L.LatLng(13, 100);
//var map = L.map('map').setView(myloc, 12);
$(function () {
$('.btn-a').on('click', function(e){
// e.preventDefault();
var clsName = $(this).val();
var lat, long;
if (clsName == 'First') {
lat = 13;
long = 100;
} else if(clasName = 'Second') {
lat = 14;
long = 101;
}
//set the myloc here
myloc = new L.LatLng(lat, long);
//then map again
//L.map('map').setView(myloc, 12)
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<input type="button" id="btn-first" class="btn-a" value = "First">
<input type="button" id="btn-second" class="btn-a" value = "Second">
</div>
Below is an approach you can use, similar to what you we're doing. The example uses event delegation to monitor button clicks and then sets the lat and long variables accordingly. Those variables are then used to update the value of the global myLoc. I used an object literal in place of your new L.LatLng object for simplicity.
let myLoc = {
lat: 13,
long: 100
};
//new L.LatLng(13, 100);
document.querySelector('.row').addEventListener('click', function(e) {
if (e.target.type === 'button') {
let lat = 0;
let long = 0;
if (e.target.id === 'btn-first') {
lat = 13;
long = 100;
} else if (e.target.id === 'btn-second') {
lat = 14;
long = 101;
}
myLoc = {
lat,
long
};
console.log(`myLoc.lat: ${myLoc.lat}; myLoc.long ${myLoc.long}`);
//new L.LatLng(lat, long);
}
});
<div class="row">
<input type="button" id="btn-first" class="btn-a" value="First">
<input type="button" id="btn-second" class="btn-a" value="Second">
</div>
$(document).ready(function () {
$('.btn-a').each(function () {
$(this).click(function () {
var $this = $(this).val();
if ($this == 'First') {
$(this).val('One');
} else if ($this == 'Second') {
$(this).val('Two');
}
})
});
});
I am messing with the google maps API and using angular, and I am having an issue binding the data from the API to a variable and displaying it correctly with an ng-repeat. The ng-repeat is supposed to list the name property of the place objects, but it does not do that unless I enter the same zipcode twice. Here is the html:
<!DOCTYPE html>
<html ng-app = "openApp">
<head>
<meta charset="utf-8">
<title>Open Sesame</title>
<script src = "http://maps.googleapis.com/maps/api/js? key=AIzaSyArO1n-5w8xxPblR_aDxV6Ul1VLik3_pRY&libraries=places"></script>
<script src = "vendors/angular/angular.min.js"></script>
<script src = "assets/scripts/composite.all.min.js"></script>
<link rel = "stylesheet" href = "assets/styles/style.css" />
</head>
<body ng-controller = "MainController as main">
<h1>Is it open?</h1>
<!-- <button ng-click = ""></button> -->
<div id = "googleMap"></div>
<form>
<input type = "text" ng-model = "main.zipcode"/>
<input type = "submit" ng-click = "main.enterZip()" />
</form>
<div id = "displayInfo">
<ul>
<li ng-repeat = "item in main.openPlaces">
test {{item.name}}
</li>
</ul>
</div>
</body>
</html>
and here is the client side javascript:
angular.module('openApp', [])
.controller('MainController', ['$http', function($http){
var vm = this;
vm.latitude;
vm.longitude;
vm.openPlaces = [];
initialize();
vm.enterZip = function(){
$http.get('/zipcodeApi/'+ vm.zipcode)
.then(function(response){
vm.latitude = response.data.lat;
vm.longitude = response.data.lng;
initialize();
})
}
function initialize(){
var mapLocation = new google.maps.LatLng(vm.latitude, vm.longitude);
var openNow = [];
var mapProp = {
center: mapLocation,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var placesRequest = {
location: mapLocation,
radius: '2000',
types: ['restaurant'],
keyword: 'restaurant',
};
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(placesRequest, function(results, status) {
if(status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var listedHours = results[i].opening_hours;
if(typeof listedHours != 'undefined' && listedHours.open_now === true){
openNow.push(results[i]);
var place = results[i];
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
}
}
}
vm.openPlaces = openNow;
})//closes nearbySearch()
}
}]);
MainController would work because you named your controller MainController in the JS file. And that's the same reason MainController as main won't work.
I'm trying to make a code that works like this:
Get number of teams (y) and number of players(x).
Get x names and x ranks.
Create balance teams based on the player ranks.
Each team should have x/y players.
Print each team separately.
I can't see where is my problem and why my code doesn't work. Hope you guys could help.
This is my code:
function step1() {
var teams = document.getElementById("teams").value;
var players = document.getElementById("players").value;
var main = document.getElementById("main");
main.innerHTML="";
for(var i=1;i<=players;i++){
main.innerHTML += "<input class='names' placeholder='Player "+i+"' type='text' style='width:100px'/> "+
"<input class='ranks' placeholder='Rank' type='text' style='width:40px'/><br/>";
}
main.innerHTML+="<br/><button onclick='buildTeams("+players+","+teams+")'>Build</button>";
}
function buildTeams(playersInt,teamsInt) {
var error=0;
var names = new Array(playersInt);
var ranks = new Array(playersInt);
var nameInp = document.getElementsByClassName("names");
var rankInp = document.getElementsByClassName("ranks");
for(var i=0;i<playersInt;i++) {
names[i] = nameInp[i].value;
}
for(var i=0;i<playersInt;i++) {
ranks[i] = rankInp[i].value;
}
var teams = new Array(teamsInt);
for(var i=0;i<teamsInt;i++) {
teams[i]=new Array(playersInt/teamsInt);
}
for(var i=0;i<(playersInt/teamsInt);i++) {
for(var j=0;j<teamsInt;j++) {
teams[i][j]=names[checkMvp(ranks)];
ranks[checkMvp(ranks)]=-1;
}
}
for(var i=0;i<teamsInt;i++) {
alert(teams[i]);
}
}
function checkMvp(ranks) {
var high= ranks[0];
var bpi=0;
for(var i=1;i<ranks.length;i++) {
if(ranks[i]>high) {
bpi=i;
}
}
return bpi;
}
<h2>Power Balance</h2>
<div id="main">
Number of teams:
<input type="text" id="teams" style="width:30px"/>
<br/><br/>
Number of players:
<input type="text" id="players" style="width:30px"/>
<br/><br/>
<p id="error"></p>
<input type="button" onclick="step1()" value="Next"/>
</div>
Check out my solution here. It should be working fine. You mistakenly swapped the logic in the loop for adding players to teams. Also, it's a good habit to use Array.prototype.push than to create new element using a loop function after creating the array with new Array(length).
function step1() {
var teams = document.getElementById("teams").value;
var players = document.getElementById("players").value;
var main = document.getElementById("main");
main.innerHTML="";
for(var i=1;i<=players;i++){
main.innerHTML += "<input class='names' placeholder='Player "+i+"' type='text' style='width:100px'/> "+
"<input class='ranks' placeholder='Rank' type='text' style='width:40px'/><br/>";
}
main.innerHTML+="<br/><button onclick='buildTeams("+players+","+teams+")'>Build</button>";
}
function buildTeams(playersInt,teamsInt) {
var error=0;
var names = [];
var ranks = [];
var nameInp = document.getElementsByClassName("names");
var rankInp = document.getElementsByClassName("ranks");
for(var i=0;i<playersInt;i++) {
names.push(nameInp[i].value);
}
for(var e=0;e<playersInt;e++) {
ranks.push(rankInp[e].value);
}
var teams = [];
for(var x=0;x<teamsInt;x++) {
teams.push([]);
}
for(var a=0;a<teamsInt;a++) {
for(var j=0;j<(playersInt/teamsInt);j++) {
console.log(teams[a]);
teams[a].push(names[checkMvp(ranks)]);
ranks[checkMvp(ranks)]=-1;
}
}
alert(teams);
for(var w=0;w<teamsInt;w++) {
alert(teams[w]);
}
}
function checkMvp(ranks) {
var high= ranks[0];
var bpi=0;
for(var i=1;i<ranks.length;i++) {
if(ranks[i]>high) {
bpi=i;
}
}
return bpi;
}
having trouble trying to get a store locator to work in javascript only. i can get the data to load, but when i search for my location with mile radius set, it goes weird, any ideas? the original idea is from a website Click here but obviously it has bugs as it doesn't load my location. This is using google maps v3. Any help would be appreciated
var StoreFinder = (new function(){
// config
var showAllLocationsOnStart = true;
// #PRIVATE variables
var userAddress, markers = [],
image = 'http://cdn1.iconfinder.com/data/icons/fatcow/32x32_0440/flag_red.png',
stores = [
{lat:53.4577, lng:-2.2735, name:'Old Tafford, Manchester'},
{lat:51.4801, lng:-0.18991, name:'Chelsea Football Club'},
{lat:51.5551, lng:-0.1097, name:'Arsenal Football Club'},
{lat:53.4846, lng:-2.2027, name:'Manchester City Football Club'}
];
/* Initialize GMaps ***********************************************/
this.the_map;
this.initialize = function(){
var usCenter = new google.maps.LatLng(52.5813, -1.4446),
myOptions = {zoom:6,center: usCenter,mapTypeId:google.maps.MapTypeId.ROADMAP};
StoreFinder.the_map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
var storeCount = stores.length;
for(i=0; i < storeCount; i++){
var marker = new google.maps.Marker({position: new google.maps.LatLng(stores[i].lat,stores[i].lng),title:stores[i].name,icon: image})
markers.push( marker )
if(showAllLocationsOnStart){ marker.setMap(StoreFinder.the_map); }
}
}
/* End Initialize *************************************************/
// #PRIVATE
function haversineDistance(p1, p2) {
function rad(x) {return x*Math.PI/180;}
var R = 3958.75587;
var dLat = rad( (p2.lat-p1.lat) );
var dLon = rad( (p2.lng-p1.lng) );
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(rad(p1.lat)) * Math.cos(rad(p2.lat)) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d;
}
// #PRIVATE get distance between two markers (GMARKER OBJECTS)
function getDist(marker1,marker2){
var p1 = { lat:marker1.position.za, lng:marker1.position.Ba },
p2 = { lat:marker2.position.za, lng:marker2.position.Ba };
return haversineDistance(p1, p2);
}
// #PUBLIC clear all markers, then display all store locations
this.showAllLocations = function(){
var storeCount = markers.length;
for(i=0; i < storeCount; i++){
markers[i].setMap(null);
markers[i].setMap(StoreFinder.the_map);
}
var usCenter = new google.maps.LatLng(52.5813, -1.4446);
StoreFinder.the_map.setCenter(usCenter);
StoreFinder.the_map.setZoom(4);
}
// #PUBLIC - geocode person's address (from form inputs), calculate distance to stores,
// then display those within X miles
this.geoCode = function(userLocation,miles){
var geocoder = new google.maps.Geocoder();
var _stores = markers; //#IMPORTANT: markers is the array of instantiated Gmarker objects (don't use the STORES variable)
geocoder.geocode({'address':userLocation},function(results,status){
if(userAddress === null || userAddress === undefined){
userAddress = new google.maps.Marker({
map:StoreFinder.the_map,
position:results[0].geometry.location
})
}else{
userAddress.setMap(null);
userAddress = new google.maps.Marker({
map:StoreFinder.the_map,
position:results[0].geometry.location
})
}
StoreFinder.the_map.setCenter( new google.maps.LatLng(userAddress.position.za, userAddress.position.Ba) );
StoreFinder.the_map.setZoom(5);
var storeCount = _stores.length,
results = 0;
for(i=0; i < storeCount; i++){
_stores[i].setMap(null);
if( getDist(_stores[i],userAddress) < miles ){
_stores[i].setMap(StoreFinder.the_map);
results++;
}
}
var str = results+' store(s) found within '+miles+' miles of your location'
$('#results').empty().append( str );
})
}
})
$(document).ready(function(){
$('#send').click(function(){
var location = $('#address').val(),
miles = $('#sl-miles').val();
if(location.length > 5){ StoreFinder.geoCode(location,miles); }else{ StoreFinder.showAllLocations(); }
})
})
</script>
</head>
<body onload="StoreFinder.initialize()" style="padding:10px;">
<div id="store_locator_sorting">
<label for="address"><span>A</span>
<input id="address" name="address" />
</label>
<label for="sl-miles"><span>Within</span>
<select id="sl-miles" name="sl-miles">
<option value="25">25 Miles</option>
<option value="50">50 Miles</option>
<option value="100">100 Miles</option>
<option value="200">200 Miles</option>
<option value="500">500 Miles</option>
</select>
</label>
<button id="send" type="button" >Find</button> <span style="font-size:11px;text-transform:uppercase;cursor:pointer;">( <a onclick="StoreFinder.showAllLocations();">Reset Map</a> )</span>
</div>
<div id="map_canvas" style="float:left;width:750px;height:530px;border:5px solid #ddd;"></div>
<div id="results" style="float:left;"></div>
Try using the position.lat() and position.lng() methods instead of position.za and position.Ba.
So your getDist function would be:
// #PRIVATE get distance between two markers (GMARKER OBJECTS)
function getDist(marker1,marker2){
var p1 = { lat:marker1.position.lat(), lng:marker1.position.lng() },
p2 = { lat:marker2.position.lat(), lng:marker2.position.lng() };
return haversineDistance(p1, p2);
}
And in your geoCode:
StoreFinder.the_map.setCenter( new google.maps.LatLng(userAddress.position.lat(), userAddress.position.lng()));