Markers not showing in map when geocoding address - javascript

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.

Related

Google Maps geocode() loop to place markers

I have an array with location data with one of the items being an address - ie. "123 Main Street, San Francisco, California". I want to take that address, turn it into coordinates, then use those coordinates to plot a marker on the map. To do this, I know I need to use geocode(), so I added that part into my loop.
If I were to use latitude and longitude in my array instead of the address, I can get this to work fine. But, since I added geocode() into my loop, I can only get the first location in the array to display a marker.
I have seen some similar questions on here that suggest using callback() but I did not understand it. I've also seen a suggestion to add a delay to geocode() of 0.5 seconds which worked for the poster, but comments said it may not load all locations on slower internet speeds.
How can I fix this to show all locations in the correct way?
// Create the map with markers.
function createmap(zoomlevel, centerpos, showDot)
{
// Create the map canvas with options.
var map = new google.maps.Map(document.getElementById('map-canvas'), {
scrollwheel: false,
draggable: true,
mapTypeControl: false,
zoom: zoomlevel,
center: new google.maps.LatLng(40.577453, 2.237408), // Center the map at this location.
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker, i;
// For each location in the array...
for (i = 0; i < locations.length; i++)
{
// Get the coordintes for the address.
var geocoder = new google.maps.Geocoder();
var address = locations[i][5]; // ***This variable will output the address.***
geocoder.geocode( { 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var location_latitude = results[0].geometry.location.lat();
var location_longitude = results[0].geometry.location.lng();
// Create the map marker icon (SVG file).
var marker_icon = {
url: '//'+domain+'/__NEW__/_backend/assets/img/map-marker.svg',
anchor: new google.maps.Point(25,50),
scaledSize: new google.maps.Size(50,50)
}
// Place the marker on the map.
var marker = new google.maps.Marker({
position: new google.maps.LatLng(location_latitude, location_longitude),
map: map,
icon: marker_icon
});
}
});
}
}
This is how I am placing map markers on Google Maps:
<script type="text/javascript">
let map;
let parameters;
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: #Model.Latitude , lng: #Model.Longitude },
zoom: #Model.Zoom,
});
#foreach (var asset in dbService.Assets)
{
#if (asset.State != Models.AssetState.deleted)
{
#:parameters = 'Id = #asset.Id\n' + 'Temperature = #asset.Temperature\n' + 'Moisture = #asset.Moisture\n';
#:setMarker('#asset.Latitude', '#asset.Longitude', '#asset.State');
}
}
}
function getIconByState(state) {
if (state == 'non_functional') {
return 'non-functional.png';
}
else if (state == 'under_maintenance') {
return 'under-maintenance.png';
}
else if (state == 'functional') {
return 'functional.png';
}
}
function setMarker(lat, lng, state) {
var markerjs = new google.maps.Marker({
icon: getIconByState(state),
position: new google.maps.LatLng(lat, lng),
});
markerjs.setMap(map);
let infowindow = new google.maps.InfoWindow({
content: parameters,
});
markerjs.addListener("click", () => {
infowindow.open(map, markerjs);
});
}
</script>
//this is how to use the callback
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR-API-KEY&callback=initMap&libraries=&v=weekly"
defer></script>
In this code, I use the latitude and longitude to place a marker on the Map.
If you want to extract the latitude and longitude from an address, then use geocoder API in the following way:
<script type="text/javascript">
function setCoordinates() {
let address = document.getElementById('zip').value;
if (address) {
let geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById('latitude').value = results[0].geometry.location.lat();
document.getElementById('longitude').value = results[0].geometry.location.lng();
}
else {
console.log('geocoding failed');
}
});
}
}
else {
alert('Please enter postal code to use this functionality');
}
}
</script>

google maps user location not loading

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
});
});
}

change centre of google map with change in city name from action method in controller

I have a simple java script code like this---
<script type="text/javascript">
$(document).ready(function () {
var localityUrl = '#Url.Action("FetchLocalities")';
var subLocalityUrl = '#Url.Action("FetchSubLocalities")';
var localities = $('#SelectedLocality');
var subLocalities = $('#SelectedSubLocality');
$('#SelectedCity').change(function () {
codeAddress();
localities.empty();
subLocalities.empty();
$.getJSON(localityUrl, { ID: $(this).val() }, function (data) {
if (!data) {
// codeAddress();
return;
}
localities.append($('<option></option>').val('').text('Please select'));
$.each(data, function (index, item) {
localities.append($('<option></option>').val(item.Value).text(item.Text));
});
});
})
and my codeAddress function is something like this--
function codeAddress() {
var lat = document.getElementById('SelectedCity').Latitude;
var lng = document.getElementById('SelectedCity').Longitude;
var myLatlng = new google.maps.LatLng(lat, lng);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
and my FetchCities action method is---
public List<City> FetchCities()
{
List<City> cities = new List<City>();
cities.Add(new City() { Id = 1 , Name = "--Select Your City--" });
cities.Add(new City() { Id = 2, Name = "Faridabaad", Latitude = 28.4211M, Longitude = 77.3078M });
cities.Add(new City() { Id = 3, Name = "Greater Noida", Latitude = 28.4962M, Longitude = 77.5360M });
return cities;
}
I want to change google map with change in city name by calling the codeAddress function. My problem is that initially google map is loading fine but there is no change in google map with city name changing.You can have a look at full code here http://pastebin.com/6HWcPg9a and my controller is--http://pastebin.com/2zy7fNTj
Plzz tell me is my codeAddress function is correct or not???will it work inside SelectedCity.change(function).What changes to be made if any plzz help me**
Right now, i have tried geocoding feature of google map and tried to pass latitude longitude but failed once again---the code is like this it's not working it's showing some other places on google map--
var address = document.getElementById('SelectedCity').value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
var latlng = new google.maps.LatLng(latitude, longitude);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder = new google.maps.Geocoder();
As far as I see there are few errors:
There are no methods nor properties like Latitude and Longitude.
You're not populating element with none of this data.
Replace this line:
$.each(data, function (index, item) {
localities.append($('<option></option>').val(item.Value).text(item.Text));
});
with that:
$.each(data, function (index, item) {
localities.append($('<option data-lat='+item.Latitude +' data-lng='+item.Longitude+'></option>').text(item.Text));
});
and this:
var lat = document.getElementById('SelectedCity').Latitude;
var lng = document.getElementById('SelectedCity').Longitude;
with that:
var lat = $('#SelectedCity').data('lat'),
lng = $('#SelectedCity').data('lng');
And one more thing. There is a nice field in MSSQL called dbgeography for storing coordinates with few nice extra properties. Google it ;-)

Google maps zoom level for country

I'm having a problem working out how to set the zoom level for different countries, I have managed to get the map working and displaying the country, just cannot seem to work out how to set the zoom level.
Any help would be appreciated.
Thanks
George
<script type="text/javascript">
var infowindow = null;
$(document).ready(function () { initialize(); });
function initialize() {
//var geocoder = new google.maps.Geocoder();
//geocoder.geocode({ 'address': address }, function (results, status) {
// if (status == google.maps.GeocoderStatus.OK) {
// map.setCenter(results[0].geometry.location);
// map.fitBounds(results[0].geometry.viewport);
// }
//});
var centerMap = new google.maps.LatLng(#Html.Raw(#item.strLatLong));
var myOptions = {
zoom: 4, //<<-------How can I chnage this
center: centerMap,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("WeatherMapLocation"), myOptions);
setMarkers(map, sites);
infowindow = new google.maps.InfoWindow({
content: "loading..."
});
var bikeLayer = new google.maps.BicyclingLayer();
bikeLayer.setMap(map);
}
function setMarkers(map, markers) {
for (var i = 0; i < markers.length; i++) {
var sites = markers[i];
var siteLatLng = new google.maps.LatLng(sites[1], sites[2]);
var marker = new google.maps.Marker({
position: siteLatLng,
map: map,
title: sites[0],
zIndex: sites[3],
html: sites[4]
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
}
}
</script>
From the documentation on the Geocoder, there is a viewport and a bounds returned in the geocoder's response which can be used to center and zoom the map on the result.
if (results && results[0] && results[0].geometry && results[0].geometry.viewport)
map.fitBounds(results[0].geometry.viewport);
working example

unable to load two markers on google map from .each loop

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

Categories

Resources