Reputation: 5
I created a website where different locations are shown per user's search. Those locations are identified by their postcodes which I previously added them in a Database. However, I would like to add Google map with markers on those locations. My plan is when the user clicks for a particular location's details, a map will pop up with the marker. So I used codes for Google map, the problem is I had to specify lat & long to get the marker. I want a code that will dynamically get those locations postcodes and marker for each.
Note: I used this code to get the map.
<script>
var myCenter=new google.maps.LatLng(51.508742,-0.120850); //I don't want this value fixed
var marker;
function initialize()
{
var mapProp = {
center:myCenter,
zoom:5,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
var marker=new google.maps.Marker({
position:myCenter,
animation:google.maps.Animation.BOUNCE
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
And this was used in view.aspx to display postcodes from database:
<%: Html.DisplayFor(modelItem => item.PostCode) %>
Upvotes: 0
Views: 1584
Reputation: 1255
You need to use search API to get lat and lng from post code :
1) Add this script to header :
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
2) Use this JavaScript function to get lat,lng by postcode :
function GetLocation() {
var geocoder = new google.maps.Geocoder();
var address = document.getElementById("txtAddress").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();
alert("Latitude: " + latitude + "\nLongitude: " + longitude);
} else {
alert("Request failed.")
}
});
};
3) Then you can use your code to pass lat and lng values
Upvotes: 1