Google Maps Javascript not getting Coordinates of user - javascript

This javascript wont get the coordinates of the user
(this is a html, js and css application only)
(the area with Bold and Italic text, is the one supposed to get the coordinates from the client)
I have tried different soloutions, and they wont work, + it doesnt show the ones if the user is within 25km
center: new google.maps.LatLng(val(coords.latitude),val(coords.longitude)),
<script type="text/javascript">
var side_bar_html = "";
var gmarkers = [];
var map = null;
var markerclusterer = null;
function createMarker(latlng, name, html) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
gmarkers.push(marker);
side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a><br>';
}
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
function initialize() {
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(val(coords.latitude),val(coords.longitude)),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
google.maps.event.addListener(map, 'click', find_closest_marker);
downloadUrl("markers.xml", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var id = markers[i].getAttribute("id");
var sted = markers[i].getAttribute("sted");
var html="<b>"+sted+"</b><br>"+id;
var marker = createMarker(point,sted+" "+id,html);
}
markerCluster = new MarkerClusterer(map, gmarkers);
document.getElementById("side_bar").innerHTML = side_bar_html;
});
}
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
function find_closest_marker( event ) {
var closestMarker = -1;
var closestDistance = Number.MAX_VALUE;
for( i=0;i<gmarkers.length; i++ ) {
var distance = google.maps.geometry.spherical.computeDistanceBetween(gmarkers[i].getPosition(),event.latLng);
if ( distance < closestDistance ) {
closestMarker = i;
closestDistance = distance;
}
}
map.setCenter(gmarkers[closestMarker].getPosition());
if (map.getZoom() < 16) map.setZoom(16);
google.maps.event.trigger(gmarkers[closestMarker], 'click');
}
</script>

You can user a simple JS function for that.
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showLatLng);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showLatLng(location) {
alert("Latitude: " + location.coords.latitude +
"Longitude: " + location.coords.longitude);
}
</script>
Hope it helps

Related

google maps Cannot read property 'maps' of undefined

i trying to display markers according to user location and i keep getting this error that as commenas it is i didnt find any solution that match my problem,
thae error i'm getiing is : Uncaught TypeError: Cannot read property 'maps' of undefined & its referring to this :at Array.filter (native) .
thanks:
<script src="https://maps.googleapis.com/maps/api/js?key="My_Api_Key"&libraries=geometry"></script>
<script>
"use strict";
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function(position) {
var markers = #Html.Raw(Json.Encode(Model.UpcomingLectureGigs));
var currentLatitude = position.coords.latitude;
var currentLongitude = position.coords.longitude;
var userLatLng = currentLatitude + currentLongitude;
var markersFiltered = markers.filter(function(markers, index, array, google) {
var myLatlng = new window.google.maps.LatLng(markers.Latitude, markers.Longitude);
return google.maps.geometry.spherical.computeDistanceBetween(userLatLng, myLatlng) < 10000;
});
window.onload = function(a) {
var mapOptions = {
center: new window.google.maps.LatLng(markers[0].Latitude, markers[0].Longitude),
zoom: 8,
mapTypeId: window.google.maps.MapTypeId.ROADMAP
};
var infoWindow = new window.google.maps.InfoWindow();
var map = new window.google.maps.Map(document.getElementById("dvMap"), mapOptions);
for (var i = 0; i < markersFiltered.length; i++) {
var data = markers[i];
var myLatlng = new window.google.maps.LatLng(data.Latitude, data.Longitude);
var marker = new window.google.maps.Marker({
position: myLatlng,
draggable: true,
animation: google.maps.Animation.DROP,
get map() { return map; }
});
(function(marker, data) {
window.google.maps.event.addListener(marker,
"click",
function(e) {
infoWindow.setContent(data.Venue + " " + data.Genre.Name);
infoWindow.open(map, marker);
});
})(marker, data);
}
};
});
};
</script>
https://jsfiddle.net/1gm0u4wd/9/
Your html will be as below. Your maps api javascript will be linked inside html section not javascript section.
<div id="map" style="width: 500px; height: 500px"/>
<script src="https://maps.googleapis.com/maps/api/js?key=yourMapsAPIKey&libraries=geometry"></script>
Note : "yourMapsAPIKey" should be your API key.
You can get your maps api key from here.
Update your script as below
"use strict";
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function(position) {
var currentLatitude = position.coords.latitude;
var currentLongitude = position.coords.longitude;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: new google.maps.LatLng(currentLatitude, currentLongitude),
});
//your dynamic markers
var markers = #Html.Raw(Json.Encode(Model.UpcomingLectureGigs));
//default marker at current location
//var markers = new google.maps.Marker({
//position: new google.maps.LatLng(currentLatitude, currentLongitude),
//map: map,
//title: 'Hello World!'
//});
var userLatLng = new window.google.maps.LatLng(currentLatitude, currentLongitude);
//your filter function
var markersFiltered = markers.filter(function(markers, index, array, google) {
var myLatlng = new window.google.maps.LatLng(markers.Latitude, markers.Longitude);
return google.maps.geometry.spherical.computeDistanceBetween(userLatLng, myLatlng) < 10000;
});
window.onload = function(a) {
var mapOptions = {
center: new window.google.maps.LatLng(markers[0].Latitude, markers[0].Longitude),
zoom: 8,
mapTypeId: window.google.maps.MapTypeId.ROADMAP
};
var infoWindow = new window.google.maps.InfoWindow();
var map = new window.google.maps.Map(document.getElementById("dvMap"), mapOptions);
for (var i = 0; i < markersFiltered.length; i++) {
var data = markers[i];
var myLatlng = new window.google.maps.LatLng(data.Latitude, data.Longitude);
var marker = new window.google.maps.Marker({
position: myLatlng,
draggable: true,
animation: google.maps.Animation.DROP,
get map() {
return map;
}
});
(function(marker, data) {
window.google.maps.event.addListener(marker,
"click",
function(e) {
infoWindow.setContent(data.Venue + " " + data.Genre.Name);
infoWindow.open(map, marker);
});
})(marker, data);
}
};
});
};
Fiddle here

sorting marker in google map according to user location

I have a list of events that I display as markers on a map(its web application/site) and I would like to show only events in a certain distance (10 KM) from the user current location So, how can I combine this 2
//User Location
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(
function (position) {
var currentLatitude = position.coords.latitude;
var currentLongitude = position.coords.longitude;
// alert ("Latitude"+currentLatitude+"Longitude"+currentLongitude);window.mapServiceProvider(position.coords.latitude,position.coords.longitude);
// console.log(position);
}
);
}
//List of location from the Db.
var markers = #Html.Raw(Json.Encode(Model.UpcomingLectureGigs));
//Set All merkers on the map
window.onload = function (a) {
var mapOptions = {
center: new window.google.maps.LatLng(window.markers[0].Latitude, window.markers[0].Longitude),
zoom: 12,
mapTypeId: window.google.maps.MapTypeId.ROADMAP
};
var infoWindow = new window.google.maps.InfoWindow();
var map = new window.google.maps.Map(document.getElementById("dvMap"), mapOptions);
for (var i = 0; i < window.markers.length; i++) {
var data = window.markers[i];
var myLatlng = new window.google.maps.LatLng(data.Latitude, data.Longitude);
// console.log(data.Latitude, data.Longitude);
var marker = new window.google.maps.Marker({
position: myLatlng,
draggable: true,
animation: google.maps.Animation.DROP,
get map() { return map; }
});
(function (marker, data) {
window.google.maps.event.addListener(marker,
"click",
function (e) {
infoWindow.setContent(data
.Venue +
" " +
data.Genre.Name +
" " +
data.DateTime.toString("dd/mm/yy"));
//.toISOString().split("T")[0]);
// .format('MM/DD h:mm');
infoWindow.open(map, marker);
});
})(marker, data);
};
};
You can use a geometry library to calculate distance in meters between the user location and marker.
https://developers.google.com/maps/documentation/javascript/reference#spherical
The code snapshot to filter markers may be something like
var markers_filtered = markers.filter(function(marker, index, array) {
var myLatlng = new window.google.maps.LatLng(marker.Latitude, marker.Longitude);
return google.maps.geometry.spherical.computeDistanceBetween(userLatLng, myLatlng) < 10000;
});
for (var i = 0; i < markers_filtered.length; i++) {
//Your stuff here
}
You should add libraries=geometry parameter when you load Maps JavaScript API.
https://developers.google.com/maps/documentation/javascript/geometry

Change co-ordinate on map

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyD83DW4cuDAMp0Zf2GkEXGFqnBAewN5qko"></script>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
</head>
<body>
<div id="map" style="width: 100%; height: 400px;"></div>
<script type="text/javascript">
function init(locations){
var element = document.getElementById("map");
var mapTypeIds = [];
for(var type in google.maps.MapTypeId) {
mapTypeIds.push(google.maps.MapTypeId[type]);
}
mapTypeIds.push("OSM");
var map = new google.maps.Map(element, {
center: new google.maps.LatLng(parseInt(locations[0].lat), parseInt(locations[0].lng)),
zoom: 6,
mapTypeId: "OSM",
mapTypeControlOptions: {
mapTypeIds: mapTypeIds
}
});
var infoWindow = new google.maps.InfoWindow(), marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].lat, locations[i].lng),
map: map,
draggable:true,
// title: locations[i].lat
// icon: image
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(locations[i].infowindow);
infoWindow.open(map, marker);
}
})(marker, i));
var mapTypeIds = [];
for(var type in google.maps.MapTypeId) {
mapTypeIds.push(google.maps.MapTypeId[type]);
}
mapTypeIds.push("OSM");
map.mapTypes.set("OSM", new google.maps.ImageMapType({
getTileUrl: function(coord, zoom) {
return "http://tile.openstreetmap.org/" + zoom + "/" + coord.x + "/" + coord.y + ".png";
},
tileSize: new google.maps.Size(256, 256),
name: "OpenStreetMap",
maxZoom: 18
}));
}
}
// long 77.4028193 lat 23.2243851
var locations = [{"lat":"21.2243851","lng":"77.4028193","infowindow":" information1 "},{"lat":"17.433282","lng":"78.426762","infowindow":" information2 "}];
var locations1 = [{"lat":"24.2243851","lng":"77.4028193","infowindow":" information1 "},{"lat":"17.434282","lng":"78.426762","infowindow":" information2 "}];
window.onload = init(locations);
window.setInterval( function(){console.log("first fn");change(locations1);}, 3500);
window.setInterval( function(){console.log("second fn");change(locations);}, 1500);
function change(locations){
console.log(locations);
var mapTypeIds = [];
for(var type in google.maps.MapTypeId) {
mapTypeIds.push(google.maps.MapTypeId[type]);
}
mapTypeIds.push("OSM");
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {lat: parseInt(locations[0].lat), lng: parseInt(locations[0].lng)},
mapTypeId: "OSM",
mapTypeControlOptions: {
mapTypeIds: mapTypeIds
}
});
// var map = google.maps.Map(document.getElementById("map"));
var infoWindow = new google.maps.InfoWindow(), marker, i;
for (i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].lat, locations[i].lng),
});
marker.setMap(map);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(locations[i].infowindow);
infoWindow.open(map, marker);
}
})(marker, i));
var mapTypeIds = [];
for(var type in google.maps.MapTypeId) {
mapTypeIds.push(google.maps.MapTypeId[type]);
}
mapTypeIds.push("OSM");
map.mapTypes.set("OSM", new google.maps.ImageMapType({
getTileUrl: function(coord, zoom) {
return "http://tile.openstreetmap.org/" + zoom + "/" + coord.x + "/" + coord.y + ".png";
},
tileSize: new google.maps.Size(256, 256),
name: "OpenStreetMap",
maxZoom: 18
}));
}
}
</script>
</body>
</html>
without reloading/refreshing googlemap markers to be replaced. Tried all the ways provided by google-map api and other blogs. nothing helping me, atlast posting here hoping someone helps me with this part.
I have copied complete code here so that it helps to get on to the issue on which I am trying to solve.
Here I do.Is this right. I modified some of your code to make sure if this what you wish. I think you just miss some detail. If this is what you want, please let me know. PS :A lot of forloop in the function change-->not a good example.XD
<script type="text/javascript">
var map;
var markersArray=[];//put all markers into this
function init(locations){
var element = document.getElementById("map");
var mapTypeIds = [];
for(var type in google.maps.MapTypeId) {
mapTypeIds.push(google.maps.MapTypeId[type]);
}
mapTypeIds.push("OSM");
map = new google.maps.Map(element, {
center: new google.maps.LatLng(parseInt(locations[0].lat), parseInt(locations[0].lng)),
zoom: 6,
mapTypeId: "OSM",
mapTypeControlOptions: {
mapTypeIds: mapTypeIds
}
});
var infoWindow = new google.maps.InfoWindow(), marker, i;
for (i = 0; i < locations.length; i++) {
var mapTypeIds = [];
for(var type in google.maps.MapTypeId) {
mapTypeIds.push(google.maps.MapTypeId[type]);
}
mapTypeIds.push("OSM");
map.mapTypes.set("OSM", new google.maps.ImageMapType({
getTileUrl: function(coord, zoom) {
return "http://tile.openstreetmap.org/" + zoom + "/" + coord.x + "/" + coord.y + ".png";
},
tileSize: new google.maps.Size(256, 256),
name: "OpenStreetMap",
maxZoom: 18
}));
}
}
var locations = [{"lat":"21.2243851","lng":"77.4028193","infowindow":" information1 "},{"lat":"20.433282","lng":"78.426762","infowindow":" information2 "}];
var locations1 = [{"lat":"24.2243851","lng":"77.4028193","infowindow":" information1 "},{"lat":"22.434282","lng":"78.426762","infowindow":" information2 "}];
var counter=0;
window.onload = init(locations);
window.setInterval( function(){
if(counter%2==0)
{
change(locations1);
}
else
{
change(locations);
}
counter++;
}, 2000);
function change(locations){
for (i = 0; i < locations.length; i++)
{
if(markersArray[i]!=null)
{
markersArray[i].setMap(null);
if (i == locations.length - 1) {
markersArray = [];
}
}
}
for (i = 0; i < locations.length; i++)
{
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].lat, locations[i].lng) });
markersArray.push(marker);
}
for (i = 0; i < markersArray.length; i++)
{
markersArray[i].setMap(map);
}
}
</script>
We had a similar problem to what you are experiencing. The way we solved it was by recalculating the bounds and recentering the map each time a new location is added. So basically we have a createMarker function that has this bit of code at the end:
const map_center = bounds.getCenter();
resultsMap.setCenter(map_center);
resultsMap.panToBounds(bounds);
resultsMap.fitBounds(bounds);
Where bounds here is your map boundaries, which can be found with the google.maps.LatLngBounds() method.
EDIT: I see you want to do it without refreshing the map, I don't think resetting the bounds refreshes the map but I could be wrong about that.

Google maps markers from xml working in Chrome, not Firefox/IE

I've got a custom google map that loads a bunch of markers from an xml doc and creates a sidebar list of all the markers as well. It works fine in Chrome but but the sidebar and markers don't load in Firefox or IE. I'm using the latest versions of all browsers on a Windows7 machine.
--I edited this to add the xml parser code since that may be the problem. I don't even remember where I got this parser code but it has been(and still is) working fine on another project with pretty similar code.
javascript...
var side_bar_html = "";
var routes = {
y: {
name: "Winter Routes",
url: "http://www.huts.org/Tests/Maps/GPSTracks/10thsystemHutsYurtsMap.kml"
},
};
var gmarkers = [];
var map = null;
// A function to create the marker and set up the event window function
function createMarker(latlng, name, html) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
icon: 'images/marker2_ltblue.png',
map: map,
suppressInfoWindows: true,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
google.maps.event.addListener(marker, 'click', function() {
// map.setZoom(9);
map.setCenter(marker.getPosition());
});
// save the info we need to use later for the side_bar
gmarkers.push(marker);
// add a line to the side_bar html
side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')" onmouseover="gmarkers['+ (gmarkers.length-1) +'].setAnimation(google.maps.Animation.BOUNCE)" onmouseout="gmarkers['+ (gmarkers.length-1) +'].setAnimation(null)">' + name + '<\/a><br>';
}
// This function picks up the click and opens the corresponding info window
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
function initialize() {
// create the map
var myOptions = {
zoom: 9,
center: new google.maps.LatLng(39.369804, -106.388725),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.TERRAIN
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Read the data from example.xml
downloadUrl("gMapsHuts.xml", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var name = markers[i].getAttribute("label");
var html = GXml.value(markers[i].getElementsByTagName("infowindow")[0]);
var category = markers[i].getAttribute("category");
var season = markers[i].getAttribute("season");
// create the marker
var marker = createMarker(point,name,html,category);
}
// put the assembled side_bar_html contents into the side_bar div
document.getElementById("side_bar").innerHTML = side_bar_html;
});
createRouteTogglers();
}
// the important function... routes[id].xxxxx refers back to the top
function toggleRoute(checked, id) {
if (checked) {
var layer = new google.maps.KmlLayer(routes[id].url, {
preserveViewport: true,
suppressInfoWindows: false
});
// store kml as obj
routes[id].obj = layer;
routes[id].obj.setMap(map);
}
else {
routes[id].obj.setMap(null);
delete routes[id].obj;
}
};
// create the Routes controls
function createRouteTogglers() {
var html = "<form><ul>";
for (var prop in routes) {
html += "<li id=\"selector-" + prop + "\"><input type='checkbox' id='" + prop + "'" +
" onclick='highlight(this,\"selector-" + prop + "\"); toggleRoute(this.checked, this.id)' \/>" +
routes[prop].name + "<\/li>";
}
html += "<\/ul><\/form>";
document.getElementById("routeLayers").innerHTML = html;
};
// Append Class on Select
function highlight(box, listitem) {
var selected = 'selected';
var normal = 'normal';
document.getElementById(listitem).className = (box.checked ? selected: normal);
};
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
xml parser...
function GXml(){}
GXml.value=value;
GXml.parse=parse;
function value(node){
if(!node){
return"";
}
var retStr="";
if(node.nodeType==3||node.nodeType==4||node.nodeType==2){
retStr+=node.nodeValue;
}else if(node.nodeType==1||node.nodeType==9||node.nodeType==11){
for(var i=0;i<node.childNodes.length;++i){
retStr+=arguments.callee(node.childNodes[i]);
}
}
return retStr;
}
function parse(textDoc){
try{
if(typeof ActiveXObject!="undefined"&&typeof GetObject!="undefined"){
var b=new ActiveXObject("Microsoft.XMLDOM");
b.loadXML(textDoc);
return b;
}else if(typeof DOMParser!="undefined"){
return(new DOMParser()).parseFromString(textDoc,"text/xml");
}else{
return Wb(textDoc);
}
}
catch(c){
P.incompatible("xmlparse");
}
try{
return Wb(textDoc);
}
catch(c){
P.incompatible("xmlparse");
return document.createElement("div");
}
}
function P(){}
P.write=function(a,b){}
;P.writeRaw=function(a){}
;P.writeXML=function(a){}
;P.writeURL=function(a){}
;P.dump=function(a){}
;P.incompatible=function(){}
;P.clear=function(){}
;
function Wb(a){
return null;
}

undefined not found ie7

IE7 is giving me an issue with a script, using Google Maps API.
When the page is loaded, it says in a alert box 'undefined not found'.
This only happens in IE7, not IE8, nor IE9. Fine in other browsers too, i guess there is a coding error. As soon as i take out JS, no warning but map doesn't work, obviously.
Here is my entire JS. Thanks in advance!
var map;
var markers = [];
var infoWindow;
var panorama;
function init_map() {
map = new google.maps.Map(document.getElementById("map"), {
//center: new google.maps.LatLng(40, -100),
zoom: 4,
mapTypeId: 'roadmap',
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
});
infoWindow = new google.maps.InfoWindow();
var address = $('#address').val();
var address_optional = $('#address_optional').val();
if (address == '' && address_optional != '1') init_location();
else searchLocations(address_optional);
}
function init_location(lat, lng, zoom) {
if (lat === undefined) lat = 40;
if (lng === undefined) lng = -100;
if (zoom === undefined) zoom = 4;
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(lat, lng),
zoom: zoom,
mapTypeId: 'roadmap',
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
});
}
$("#next").live('click', function(event) {
event.preventDefault();
var page_number = $('body').data("page_number");
$('body').data("page_number", (page_number + 1));
searchLocations();
});
$("#previous").live('click', function(event) {
event.preventDefault();
var page_number = $('body').data("page_number");
$('body').data("page_number", (page_number - 1));
searchLocations();
});
function searchLocations() {
var address = $('#address').val();
var geocoder = new google.maps.Geocoder();
var address_optional = $('#address_optional').val();
geocoder.geocode({
address: address
}, function(results, status) {
if ((status == google.maps.GeocoderStatus.OK)) {
searchLocationsNear(results[0].geometry.location);
} else {
if (address_optional == '1') {
searchLocationsNear('', 1);
} else {
alert(address + ' not found');
}
}
});
}
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
var option = document.createElement("option");
option.value = "none";
option.innerHTML = "See all results:";
}
function createSidebarEntry(markerNum, sidebarContent, markerContent, lat, lng) {
var div = document.createElement('div');
div.innerHTML = sidebarContent;
div.style.cursor = 'pointer';
div.style.marginBottom = '5px';
div.onclick = function() {
infoWindow.setContent(markerContent);
infoWindow.open(map, markers[markerNum]);
init_location(lat, lng, 16);
var latlng = new google.maps.LatLng(
parseFloat(lat), parseFloat(lng));
createMarker(latlng, lat, lng, markerContent);
}
return div;
}
function resizeMap(width, height) {
$('#map').animate({
width: width,
height: height
}, function() {
google.maps.event.trigger(map, 'resize');
map.setCenter(map.getCenter());
});
}
function streetView(lat, lng) {
var dom = 'streetview';
panorama = new google.maps.StreetViewPanorama(document.getElementById(dom));
displayStreetView(lat, lng, dom);
if ($('#map').height() == 600) {
resizeMap(850, 300);
$('#streetview').height(300);
}
}
function searchLocationsNear(center, address_optional) {
clearLocations();
var sidebar = document.getElementById('sidebar');
sidebar.innerHTML = '';
var page_number = $('body').data("page_number");
if (page_number == null) {
page_number = 1;
$('body').data("page_number", page_number);
}
var categoryid = $('#categoryid').val();
if (address_optional == '1') var searchUrl = 'map_data.php?categoryid=' + categoryid + '&page_number=' + page_number + '&address_optional=' + address_optional;
else var searchUrl = 'map_data.php?lat=' + center.lat() + '&lng=' + center.lng() + '&categoryid=' + categoryid + '&page_number=' + page_number;
//alert(searchUrl);
$.ajax({
type: 'GET',
url: searchUrl,
dataType: 'json',
success: function(msg) {
var locations = msg.locations;
var markersContent = msg.markersContent;
var sidebarContent = msg.sidebarContent;
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < locations.length; i++) {
var name = locations[i]['name'];
var address = locations[i]['address'];
var distance = parseFloat(locations[i]['distance']);
var latlng = new google.maps.LatLng(
parseFloat(locations[i]['lat']), parseFloat(locations[i]['lng']));
var sidebarEntry = createSidebarEntry(i, sidebarContent[i], markersContent[i], locations[i]['lat'], locations[i]['lng']);
sidebar.appendChild(sidebarEntry);
createOption(name, distance, i);
createMarker(latlng, locations[i]['lat'], locations[i]['lng'], markersContent[i]);
bounds.extend(latlng);
}
$('#pagination').html(msg.pagination);
map.fitBounds(bounds);
}
});
resizeMap(850, 600);
$('#streetview').html('').height(0);
}
function createMarker(latlng, lat, lng, html) {
var marker = new google.maps.Marker({
map: map,
position: latlng,
animation: google.maps.Animation.DROP
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, this);
});
$("#sidebar div").click(function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
markers.push(marker);
}
function createOption(name, distance, num) {
var option = document.createElement("option");
option.value = num;
option.innerHTML = name + "(" + distance.toFixed(1) + ")";
}
function displayStreetView(lat, lng, dom) {
var latlng = new google.maps.LatLng(lat, lng);
var panoramaOptions = {
position: latlng,
pov: {
heading: 270,
pitch: 0,
zoom: 1
}
};
panorama = new google.maps.StreetViewPanorama(document.getElementById(dom), panoramaOptions);
map.setStreetView(panorama);
}

Categories

Resources