I can create a webpage that takes the name, address, lat and long of many businesses in a specific city and have put them into an embedded google map on my page. The connection to the database works, putting up the markers on the map works, however what I can't figure out from any examples, including those on Googles developers page, is how to user a user's location instead of the default coord in the googlemap.js file. What am I missing here?
var map;
var geocoder;
function loadMap() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map = new google.maps.Map(document.getElementById('map'),
{
zoom: 14,
center: pos
});
});
}
var marker = new google.maps.Marker({
// position: pune,
map: map
});
var cdata = JSON.parse(document.getElementById('data').innerHTML);
geocoder = new google.maps.Geocoder();
codeAddress(cdata);
var allData = JSON.parse(document.getElementById('allData').innerHTML);
showAllHonda(allData)
}
function showAllHonda(allData) {
var infoWind = new google.maps.InfoWindow;
Array.prototype.forEach.call(allData, function(data){
var content = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = data.name;
content.appendChild(strong);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map
});
marker.addListener('click', function(){
infoWind.setContent(content);
infoWind.open(map, marker);
})
})
}
function codeAddress(cdata) {
Array.prototype.forEach.call(cdata, function(data){
var address = data.name + ' ' + data.address;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == 'OK') {
map.setCenter(results[0].geometry.location);
var points = {};
points.id = data.id;
points.lat = map.getCenter().lat();
points.lng = map.getCenter().lng();
updateHondaWithLatLng(points);
} else {
alert('Geocode was not successful for the following reason: ' + status)
}
});
});
}
To find user's position you can use navigator.geolocation :
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map = new google.maps.Map(document.getElementById('map'),
{
zoom: 14,
center: pos
});
});
}
Related
I have made a map with getting the current location,inside the getPosition is getting also the place name which I also made a reverse geocoding that returns the place name from a coordinate, I wonder what's wrong my code that it did not return the place name and even the marker with my code for reverse geocoding.
In the console I get this
<p id="curr" style="">current lat lng</p>
function getPosition() {
navigator.geolocation.getCurrentPosition(position => {
currentLatLon = [position.coords.latitude, position.coords.longitude];
infowindow = new google.maps.InfoWindow();
map = new google.maps.Map(
document.getElementById('map'), {
center: new google.maps.LatLng(...currentLatLon),
zoom: 20
});
var geocoder = new google.maps.Geocoder();
service = new google.maps.places.PlacesService(map);
document.getElementById("curr").innerHTML=currentLatLon;
geocodeLatLng(geocoder,map,infowindow);
});
}
function geocodeLatLng(geocoder, map, infowindow) {
var input = document.getElementById('curr').value;
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
I'm working with Google Maps API for a project and I'm stuck with this Geociding thing for days...
I need to use geocoding to go in reverse and get the lat and lng from a given address, so I need these functions to create the location points.
var glocations = [];
var locations = [];
var infoWindow = new google.maps.InfoWindow({content: ''});
var geocoder;
var map;
function initMap() {
var center = new google.maps.LatLng(40.6976637,-74.1197637);
var mapOptions = {
zoom: 8,
center: center,
mapTypeControl: false,
fullscreenControl: false,
mapTypeId: google.maps.MapTypeId.TRAFFIC,
styles: []
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
geocoder = new google.maps.Geocoder();
locations = [
['0', '','Title', codeAddressLat('brooklyn', '0'), codeAddressLng('brooklyn', '0'), 'category-1', 'https://sat.ptvtelecom.net/img/red.png'],//this doesn't work
['1', '', 'Title', 40.6976637,-74.1197637, 'category-2', 'https://sat.ptvtelecom.net/img/green.png']//this works
];
for (i = 0; i < locations.length; i++) {
var url = locations[i][6];
addMarker(locations[i], url);
}
}
function addMarker(marker, url) {
var category = marker[5];
var title = marker[1];
var pos = new google.maps.LatLng(marker[3], marker[4]);
var content = marker[2];
var icon = {
url: url,
scaledSize: new google.maps.Size(32, 32)
};
marker1 = new google.maps.Marker({
title: title,
icon: icon,
position: pos,
category: category,
map: map
});
glocations.push(marker1);
google.maps.event.addListener(marker1, 'click', (function (marker1, content) {
return function () {
infoWindow.setContent(content);
infoWindow.open(map, marker1);
map.panTo(this.getPosition());
map.setZoom(20);
}
})(marker1, content));
}
function codeAddressLat(address, index) {
geocoder.geocode({ 'address': address }, function (results, status) {
var latLng = {lat: results[0].geometry.location.lat (), lng: results[0].geometry.location.lng ()};
var lat = latLng.lat;
if (status == 'OK') {
locations[index][3] = lat;//this will change the lat value, but it won't show on map
//return lat;//this will return undefined lat
}
});
}
function codeAddressLng(address, index) {
geocoder.geocode({ 'address': address }, function (results, status) {
var latLng = {lat: results[0].geometry.location.lat (), lng: results[0].geometry.location.lng ()};
var lng = latLng.lng;
if (status == 'OK') {
locations[index][4] = lng;//this will change the lng value, but it won't show on map
//return lng;//this will return undefined lng
}
});
}
initMap();
Okay, so I have three outputs here:
If I write down the lat and long values directly, the location will get the float values and the marker show in the map.
If I manipulate the locations array, the location will get float values and the marker won't show in the map.
If the functions return the values, the location will get undefined values and the marker won't show in the map.
You can see what the output looks like in the following screenshot(just url, I can't post images):
sat.ptvtelecom.net/img/result.png
Any help would be so much appreciate.
its working fine but i have one problem which is that when i open a info window its opened but when i open other info window. the last one info window still opened. but i want to close it when we open new inf window
<script>
window.onload = getMyLocation;
var geocoder;
var map;
function getMyLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayLocation);
} else {
alert("Oops, no geolocation support");
}
}
//This function is inokved asynchronously by the HTML5 geolocation API.
function displayLocation(position) {
//The latitude and longitude values obtained from HTML 5 API.
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
//Creating a new object for using latitude and longitude values with Google map.
var latLng = new google.maps.LatLng(latitude, longitude);
showMap(latLng);
addNearByPlaces(latLng);
createMarker(latLng);
//Also setting the latitude and longitude values in another div.
// var div = document.getElementById("location");
//div.innerHTML = "You are at Latitude: " + latitude + ", Longitude: " + longitude;
}
function showMap(latLng) {
geocoder = new google.maps.Geocoder();
var markers = [];
//Setting up the map options like zoom level, map type.
var mapOptions = {
center: latLng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//Creating the Map instance and assigning the HTML div element to render it in.
map = new google.maps.Map(document.getElementById("googlemap"), mapOptions);
// Create the search box and link it to the UI element.
}
function addNearByPlaces(latLng) {
var nearByService = new google.maps.places.PlacesService(map);
var request = {
location: latLng,
radius: 500,
types: ['atm']
};
nearByService.nearbySearch(request, handleNearBySearchResults);
}
function handleNearBySearchResults(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(place.geometry.location, place);
}
}
function createMarker(latLng, placeResult) {
var markerOptions = {
position: latLng,
map: map,
animation: google.maps.Animation.DROP,
clickable: true
}
//Setting up the marker object to mark the location on the map canvas.
var marker = new google.maps.Marker(markerOptions);
if (placeResult) {
var content = "<b>Name : </b>"+placeResult.name+"<br/><b>Address : </b>"+placeResult.vicinity+"<br/><b>Type : </b>"+placeResult.types+"<br/> Rating : "+placeResult.rating+"<br/>" ;
addInfoWindow(marker, latLng, content);
}
else {
var content = "You are here: ";
addInfoWindow(marker, latLng, content);
}
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
<!-- alert("Latitude: " + latitude + "\nLongitude: " + longitude); -->
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
var latLngs = new google.maps.LatLng(latitude, longitude);
addNearByPlaces(latLngs);
createMarker(latLngs);
});
}
function addInfoWindow(marker, latLng, content) {
var infoWindowOptions = {
content: content,
position: latLng
};
var infowindow = new google.maps.InfoWindow(infoWindowOptions);
google.maps.event.addListener(marker, 'click', function() {
if(!marker.open){
infowindow.open(map,marker);
marker.open = true;
}
else{
infowindow.close();
marker.open = false;
}
});
}
</script>
I use something like this for closing all infoWindows:
infoWindows = []; //variable to store all infoWindows
function createMarker( map, latlng, title, content, icon ) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: icon,
title: title
});
var infoWindow = new google.maps.InfoWindow({
content: content
});
infoWindows.push( infoWindow );
google.maps.event.addListener(marker, 'click', function () {
closeAllInfoWindows();
infoWindow.open(map, marker);
});
}
function closeAllInfoWindows() {
for (var i=0;i<infoWindows.length;i++) {
infoWindows[i].close();
}
}
am trying to load two markers over the googlemap but it appears that the map is loaded twice and i cant see both of the markers.Here is the code.
var geocoder;
var map;
geocoder = new google.maps.Geocoder();
// var address = document.getElementById("address").value;
// var user='33936357';
$.getJSON("http://api.twitter.com/1/users/lookup.json?user_id=33936357,606020001&callback=?", function (data) {
$.each(data, function (i, item) {
var screen_name = item.screen_name;
var img = item.profile_image_url;
var location = item.location;
geocoder.geocode({
address: location
}, function (response, status) {
if (status == google.maps.GeocoderStatus.OK) {
var x = response[0].geometry.location.lat(),
y = response[0].geometry.location.lng();
var mapOptions = {
center: new google.maps.LatLng(x, y),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var marker = new google.maps.Marker({
icon: img,
title: screen_name,
map: map,
position: new google.maps.LatLng(x, y)
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
});
});
I dont know how to fix this
Your map creation is within the each loop .. try this :
// setup the map objects
var geocoder = new google.maps.Geocoder();;
var mapOptions = {
center: new google.maps.LatLng(0, 0),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// added this
var bounds = new google.maps.LatLngBounds();
// create the map
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
$.getJSON("http://api.twitter.com/1/users/lookup.json?user_id=33936357,606020001&callback=?", function (data) {
$.each(data, function (i, item) {
var screen_name = item.screen_name;
var img = item.profile_image_url;
var location = item.location;
geocoder.geocode({
address: location
}, function (response, status) {
if (status == google.maps.GeocoderStatus.OK) {
var x = response[0].geometry.location.lat(),
y = response[0].geometry.location.lng();
var myLatLng = new google.maps.LatLng(x, y);
var marker = new google.maps.Marker({
icon: img,
title: screen_name,
map: map,
position: myLatLng
});
bounds.extend(myLatLng);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
});
map.fitBounds(bounds);
});
Now you create the map one .. add the long and lat to a LatLngBounds object then set the map to fit the Bounds.
Docs on LatLngBounds here
I am quite a novice with javascript stuff and am currently faking it till i make it lol and now ive come across a small hill that i'm struggling to get over :S.
Currently my script finds the users location and adds a pin to the map while copying LatLon to some form fields.
In addition to just zooming in on the users location i would like them to have the ability to add a custom address which is entered into a text field, geocoded and then updates the current pin on the map.
This all works, although it adds an additional pin to the map rather than updating the current pin.
I am unsure how to pass the value from the address geocoding function back into the original pin / or do i delete the original pin and add a new pin. I'm sure i can reuse some functions as well... i don't think my code is terribly efficient :/
Any way i hope a guru out there can help me out
Cheers
Nick
var geocoder;
var map;
var pos;
function initialize() {
geocoder = new google.maps.Geocoder();
var newyork = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
var address = document.getElementById("address").value;
var initialLocation;
var myOptions = {
zoom: 12,
center: initialLocation,
mapTypeId: google.maps.MapTypeId.TERRAIN
}
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var marker = new google.maps.Marker({
map: map,
position: pos,
title: 'Location found using HTML5.',
draggable: true
});
var lat = position.coords.latitude
var lng = position.coords.longitude
document.getElementById('geo_latitude').value=lat;
document.getElementById('geo_longitude').value=lng;
google.maps.event.addListener(marker, "dragend", function(event) {
var lat = event.latLng.lat()
var lng = event.latLng.lng()
var infowindow = new google.maps.InfoWindow({
content: '<b><?php _e('Latitude:');?></b>' + lat + '<br><b><?php _e('Longitude:');?></b>' + lng
});
infowindow.open(map, marker);
google.maps.event.addListener(marker, "dragstart", function() {
infowindow.close();
});
document.getElementById('geo_latitude').value=lat;
document.getElementById('geo_longitude').value=lng;
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else if (google.gears) {
browserSupportFlag = true;
var geo = google.gears.factory.create('beta.geolocation');
geo.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
map.setCenter(initialLocation);
}, function() {
handleNoGeoLocation(browserSupportFlag);
});
// Browser doesn't support Geolocation
} else {
browserSupportFlag = false;
handleNoGeolocation(browserSupportFlag);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag == true) {
alert("Geolocation service failed.");
initialLocation = newyork;
} else {
alert("Your browser doesn't support geolocation. We've placed you in New York.");
initialLocation = newyork;
}
map.setCenter(initialLocation);
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
//-------------------------------------------------------End initialize
function findAddress(address) {
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var pos = results[0].geometry.location;
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
To 'move' your existing marker, you'll wanna make sure its global and then you can just update its position within the findAddress function with something like:
marker.setPosition(results[0].geometry.location);